203. 移除链表元素

 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 {
11 public:
12     ListNode* removeElements(ListNode* head, int val) 
13     {
14         ListNode* dummy = new ListNode(-1);
15         ListNode* pre = dummy;
16         while(head)
17         {
18             if(head->val != val)
19             {
20                 pre->next = head;
21                 pre = pre->next;
22             }
23             head = head->next;
24         }
25         pre->next = NULL;//必须加
26         return dummy->next;
27 
28     }
29 };

 

posted @ 2020-04-04 15:28  Jinxiaobo0509  阅读(130)  评论(0)    收藏  举报