http://www.programcreek.com/2014/04/leetcode-remove-linked-list-elements-java/
http://www.jiuzhang.com/solutions/remove-linked-list-elements/
http://www.programcreek.com/2014/04/leetcode-remove-linked-list-elements-java/
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 Return: 1 --> 2 --> 3 --> 4 --> 5The key to solve this problem is using a helper node to track the head of the list.
http://www.jiuzhang.com/solutions/remove-linked-list-elements/
http://www.programcreek.com/2014/04/leetcode-remove-linked-list-elements-java/
public ListNode removeElements(ListNode head, int val) { ListNode dummy = new ListNode(0); dummy.next = head; head = dummy; while (head.next != null) { if (head.next.val == val) { head.next = head.next.next; } else { head = head.next; } } return dummy.next; }https://leetcode.com/discuss/33142/iterative-short-java-solution
public ListNode removeElements(ListNode head, int val) {
while (head != null && head.val == val) head = head.next;
ListNode curr = head;
while (curr != null && curr.next != null)
if (curr.next.val == val) curr.next = curr.next.next;
else curr = curr.next;
return head;
}
X. Recursive Version
public ListNode removeElements(ListNode head, int val) {
if (head == null) return null;
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}
public ListNode removeElements(ListNode head, int val) {
if(head == null) return null;
ListNode next = removeElements(head.next, val);
if(head.val == val) return next;
head.next = next;
return head;
}
http://www.sigmainfy.com/blog/leetcode-remove-linked-list-elements-iterative-vs-recursive.htmlpublic ListNode removeElements(ListNode head, int val) { if (head == null) { return null; } if (head.val == val){ head = removeElements(head.next, val); } else { head.next = removeElements(head.next, val); } return head; }