Removes the element of the specified value in the linked list, taking into account the head pointer, return.
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Removeelements (listnode* head,intval) {ListNode* Newhead =NewListNode ( $); Newhead->next =Head; ListNode* Pre =Newhead; ListNode* cur =Head; while(cur!=NULL) { if(Cur->val = =val) {cur= cur->Next; Pre->next =cur; } Else{cur= cur->Next; Pre= pre->Next; } } returnNewhead->Next; }};
In the beginning did not think of using recursive writing, discussion provides the following wording, very concise. Recursive to the tail of the list, and then back to the layer.
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Removeelements (listnode* head,intval) { if(head==NULL)returnNULL; Head->next = Removeelements (head->Next, Val); returnHead->val = = val? Head->Next:head; }};
[Leetcode note]-203-remove Linked List Elements