203. 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

删除链表中跟val相同的节点

C++(32ms):

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