First, the topic
1, examining
2. Analysis
Removes a node with a value of Val in the linked list.
Second, the answer
1, Ideas:
Method One,
Create a header node, and delete the value in Val one by one.
PublicListNode removeelements (ListNode head,intval) { if(Head = =NULL)return NULL; ListNode Fakehead=NewListNode (0); while(Head! =NULL&& Head.val = = val)//dealing with head nodes.Head =Head.next; Fakehead.next=Head; while(Head! =NULL&& Head.next! =NULL) { if(Head.next.val = =val) Head.next=Head.next.next; ElseHead=Head.next; } returnFakehead.next; }
Optimization: Use pre, cur pointers to make the code more concise
PublicListNode RemoveElements3 (ListNode head,intval) { if(Head = =NULL)return NULL; ListNode Fakehead=NewListNode (0); Fakehead.next=Head; ListNode Curr= Head, prev =Fakehead; while(Curr! =NULL) { if(Curr.val = =val) Prev.next=Curr.next; Elseprev=Prev.next; Curr=Curr.next; } returnFakehead.next; }
Method Two,
Using recursion
Public int val) { ifnull) return NULL ; = removeelements (Head.next, Val); return Head.val = = val? head.next:head; }
203. Remove Linked List Elements