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.

Wrong Edition.

 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) return head;
13         if(!head->next) return head->val == val ? NULL : head;
14         
15         while(head->val == val)
16             head = head->next; //avoid the case where continuous val at the head
17         if(!head) return NULL;
18         
19         ListNode* current = head;
20         while(current){
21             if(current->next->val == val){
22                 ListNode* temp = current->next;
23                 while(temp && temp->val == val)
24                     temp = temp->next;
25                 current->next = temp;
26             }
27             current = current->next;
28         }
29         return head;
30     }
31 };
View Code

Runtime: 36ms

 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) return head;
13         
14         ListNode* pre = new ListNode(0);
15         pre->next = head;
16         ListNode* move = pre;
17         
18         while(move->next){
19             if(move->next->val == val)
20                 move->next = move->next->next;
21             else
22                 move = move->next;
23         }
24         return pre->next;
25     }
26 };
原文地址:https://www.cnblogs.com/amazingzoe/p/4860045.html