Remove all elements from a linked list of integers, that has value val.
Example
Given: 1---2--and 6---3---4---5, val = 6
Return: 1--2--and 3--4--5
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Wrong Edition.
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 classSolution {Ten Public: Onelistnode* removeelements (listnode* head,intval) { A if(!head)returnhead; - if(!head->next)returnHead->val = = val?Null:head; - the while(Head->val = =val) -Head = head->next;//avoid the case where continuous Val at the head - if(!head)returnNULL; - +listnode* current =head; - while(current) { + if(Current->next->val = =val) { Alistnode* temp = current->Next; at while(temp && Temp->val = =val) -temp = temp->Next; -Current->next =temp; - } -Current = Current->Next; - } in returnhead; - } to};
View Code
Runtime:36ms
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 classSolution {Ten Public: Onelistnode* removeelements (listnode* head,intval) { A if(!head)returnhead; - -listnode* pre =NewListNode (0); thePre->next =head; -listnode* move =Pre; - - while(move->next) { + if(Move->next->val = =val) -Move->next = move->next->Next; + Else Amove = move->Next; at } - returnPre->Next; - } -};
Remove Linked List Elements