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
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */ /*problem-solving ideas: To be divided into Val in the head, in the tail, in the middle of the chain list to create a new head node, so that the list has an empty node as the head, and then only need to consider the list of links between the middle and the tail of the list of two cases*/ classSolution { Public: ListNode* Removeelements (listnode* head,intval) { if(Head = =NULL)returnHead; ListNode* Temphead =NewListNode (0); Temphead->next =Head; ListNode* Pre =Temphead; ListNode* cur =Head; while(cur) {if(Cur->val = = Val && cur->next! =NULL) {ListNode* ptr =cur; Cur= cur->Next; Pre->next = ptr->Next; Free(PTR); } Else if(Cur->val = = Val && Cur->next = =NULL) {cur= cur->Next; Pre->next =cur; } Else{Pre= pre->Next; Cur= cur->Next; } } returnTemphead->Next; }};
Remove Linked List Elements