leetcode Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

 
 
感觉并不难啊。
就是遍历就好了,至今对于链表的很多题目也只有遍历一种方法吧,避免不了的要遍历。
这个题目要注意的点是:
(1)如果删除的点都在头部怎么办,最后肯定是要返回空的。
(2)删除尾部节点应该注意的。
就是三种点:头部点,尾部点,中间的点。
 
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* removeElements(ListNode* head, int val) {
12         if(head==NULL) return head;
13         ListNode* p,*q;
14         while(head->val==val) {
15             if(head->next==NULL){head=head->next;return head;}
16             head=head->next;
17         }
18         p=head,q=head->next;
19         while(q!=NULL){
20             if(q->val==val) {
21                 if(q->next==NULL) p->next=NULL;
22                 p->next=q->next;
23                 q=q->next;}
24             else {p=q;
25                   q=q->next;
26             }
27         }
28         return head;
29     }
30 };
原文地址:https://www.cnblogs.com/LUO77/p/5053110.html