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
Title: Requires you to delete all nodes in a linked list that are equal to Val
The topic is to set up a helper variable to hold the previous node of the node being traversed, so you can delete it.
/** 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)returnHead; ListNode* temp=head,*Pre; Pre->next=temp; for(;temp->next;) { if(val==temp->val) {Temp->val=temp->next->Val; Temp->next=temp->next->Next; } Else{Pre=pre->Next; Temp=temp->Next; } } if(val==temp->val)if(pre->next==Head)//If Next of the pre points to head, indicating that the value of the node in the list is all Val and returns nullreturnNULL; Elsepre->next=null;//Otherwise, next of the pre will point to NULLreturnHead; }};
Leetcode Remove Linked List Elements