203. Remove Linked List Elements

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

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

 技巧:处理linked list问题时,当需要删除节点而不确定头节点会不会被删除时,可以考虑加一个dummy node做为新的头节点,从而将原本的头节点变成一个一般节点。
linked list的细节问题:当做while循环时,需要想清楚,当前需要处理的节点是谁,需要考虑的节点是谁。prev,curr,next等节点是常常需要想清楚的。
 
对于本题来说,while loop时,以判断curr->next是否存在为条件更为简单,因为此时curr已经处理完,不需考虑,如果next值是给定的value,则跳过:
 
 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* dummy = new ListNode(0);
13         dummy->next = head;
14         ListNode* curr = dummy;
15         while(curr->next){  //always check its next point
16             if(curr->next->val==val){      
17                 curr->next = curr->next->next;  
18             }
19             else{
20                 curr=curr->next;
21             }
22         }
23         
24         curr = dummy->next;
25         delete dummy;
26         return curr;
27     }
28 };

 

posted @ 2018-07-25 20:53  回到明天  阅读(93)  评论(0编辑  收藏  举报