Remove Linked List ElementsTotal accepted:8053 Total submissions:29898my submissions QuestionSolution
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.
Hide TagsLinked ListHas you met this question in a real interview? Yes No
Discuss
The problem is that by removing the points in the list that are the same as the given Val value, you remove the nodes in the list, which is likely to remove three (the head node, the middle node, the tail node)
So I only consider the problem of the head node in the first while loop, then the three pointer ptr1,ptr2 points to the current front and back, and PTR points to the current node.
#include <iostream>using namespace std;//definition for singly-linked list.struct listnode {int val; ListNode *next; ListNode (int x): Val (x), Next (NULL) {}}; listnode* removeelements (listnode* head, int val) {listnode* ptr0=head; listnode* Ptr=head; listnode* Ptr1=head; listnode* ptr2=head;if (Head==null) return Head;while (1) {if (ptr0->val!=val) {if (ptr0->next==null) return ptr0; Ptr1=ptr0;ptr=ptr0->next;break;} Else{ptr=ptr0->next;free (PTR0); if (ptr==null) return ptr;elseptr0=ptr;}} Ptr1=ptr0;ptr=ptr0->next;while (1) {if (ptr->next==null) {if (ptr->val==val) {ptr1->next=null;free (PTR); return PTR0;} Elsereturn Ptr0;} Else{ptr2=ptr->next;if (ptr->val==val) {ptr1->next=ptr2;free (PTR);p tr=ptr2;ptr2=ptr->next;} Else{ptr1=ptr1->next;ptr=ptr->next;ptr2=ptr2->next;}}} return PTR0;} int main () {}
leetcode_203 title--remove Linked list Elements (linked list)