Leetcode Remove Linked List Elements
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 --> 5
解题思路:
方法一:
使用“哑节点”记录链表头部。
需要使用一个变量cur记录当前节点。
The key to solve this problem is using a helper node to track the head of the list.
方法二:
使用递归recursion
Java code:
Method1
//The key to solve this problem is using a helper node to track the head of the list. public ListNode removeElements(ListNode head, int val) { ListNode dummy = new ListNode(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; } } return dummy.next; }
Method2
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; }
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/