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.
Subscribe to see which companies asked this question
It's not hard to feel. is to traverse the good, so far for the list of many problems can only traverse a method bar, can not avoid to traverse. The point to note on this topic is: (1) If the deleted points are in the head what to do, the final must be returned empty. (2) Remove the tail node should be noted. There are three kinds of points: the head point, the tail point, the middle point.
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* removeelements (listnode* head,intval) { A if(Head==null)returnhead; -listnode* p,*Q; - while(head->val==val) { the if(Head->next==null) {head=head->next;returnhead;} -Head=head->Next; - } -P=head,q=head->Next; + while(q!=NULL) { - if(q->val==val) { + if(q->next==null) p->next=NULL; AP->next=q->Next; atQ=q->next;} - Else{p=Q; -Q=q->Next; - } - } - returnhead; in } -};
Leetcode Remove Linked List Elements