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.
This problem requires the use of a pointer to the head node of a small tip, otherwise need to special first handle the head pointer, processing is much more complex.
Use a pointer to the head node so that the process can be unified. The traversal uses two pointers, one pointing to the current node, and one to the previous node of the current node. Updates the value of two pointers when the value of the current node is not the same as Val, and when the current node's value and Val value are the same, the current node is deleted and both pointers are updated.
Runtime:32ms
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: listnode* removeelements (listnode* head, int val) { ListNode * proot=new listnode (0); proot->next=head; ListNode * Cur=head; ListNode * PRE=PROOT; while (cur) { if (cur->val!=val) { pre=cur; cur=cur->next; } else { pre->next=cur->next; cur=pre->next; } } Return proot->next; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode203:remove Linked List Elements