203. Remove Linked List Elements 删除链表中val

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

 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 *pre = new ListNode(-1), *cur = pre;
13         pre->next = head;
14         while (cur->next != nullptr) {
15             if (cur->next->val == val) {
16                 ListNode *t = cur->next;
17                 cur->next = cur->next->next;
18                 t->next = nullptr;
19                 delete t;
20             } else {
21                 cur = cur->next;
22             }
23         }
24         return pre->next;
25     }
26 };

 

posted @ 2017-10-24 19:41  绿宝宝怪  阅读(143)  评论(0编辑  收藏  举报
#site_nav_under,#ad_under_post_holder,#under_post_news,#google_ad_c2,#under_post_kb{ width:0; height:0; display:none; overflow:hidden; }