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
Problem Solving Ideas:
Method One:
Use dummy node to record the head of the linked list.
You need to use a variable cur to record the current node.
The key to solve this problem are using a helper node to track the head of the list.
Method Two:
Using recursive recursion
Java Code:
Method1
//The key to solve this problem are using a helper node to track the head of the list. PublicListNode removeelements (ListNode head,intval) {ListNode dummy=NewListNode (0); Dummy.next=Head; ListNode cur=dummy; while(cur!=NULL&& cur.next!=NULL) { if(Cur.next.val = =val) {Cur.next=Cur.next.next; }Else{cur=Cur.next; } } returnDummy.next; }
Method2
Public int val) { ifnullreturnnull; = removeelements (Head.next, Val); return Head.val = = val? head.next:head; }
Reference:
1. http://bookshadow.com/weblog/2015/04/24/leetcode-remove-linked-list-elements/
2. http://www.programcreek.com/2014/04/leetcode-remove-linked-list-elements-java/
Leetcode Remove Linked List Elements