Difficulty: how to deal with head point; Considering one node, two node, and last node.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode* cur=head; ListNode* pre=NULL; //if(!head) return NULL; while(head && head->val==val ) { ListNode* temp=head; head=head->next; delete temp; } if(!head) return NULL; cur=head->next; pre=head; while(cur ){ if(cur->val==val){ pre->next=cur->next; delete cur; cur=pre->next; } else{ cur=cur->next; pre=pre->next; } } return head; //bug codes: /*for( ; cur&&cur->next ; pre=cur,cur=cur->next){ if(cur->val==val){ //ListNode* temp=cur->next; pre->next=cur->next; delete cur; cur=pre; } //pre=cur; //cur=cur->next; }*/ } }; |
Another way to deal with head point is creating a fake head pointer which can refer to
http://www.bubuko.com/infodetail-761875.html
http://yucoding.blogspot.com/2015/06/leetcode-question-remove-linked-list.html
Reference:
http://binwu.net/leetcode/2015/04/25/Leetcode-Remove-Linked-List-Elements/
没有评论:
发表评论