Leetcode 82. Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
解题思路:
关键是要设置一个dummy作为链表的开始。开始一直想用两个指针,但是一直混乱。看了答案后,答案只用了一个指针,思路一样。关键要理清楚。
Java code :
1.
public ListNode deleteDuplicates(ListNode head) { if(head == null) { return null; } ListNode dummy = new ListNode(0); dummy.next = head; ListNode p1 = dummy; while(p1.next!= null && p1.next.next !=null) { if(p1.next.val == p1.next.next.val) { int value = p1.next.val; while(p1.next!= null && value == p1.next.val) { p1.next = p1.next.next; } }else { p1 = p1.next; } } return dummy.next; }Reference:
2. 九章算法又做了一遍,思路完全一样。2016.01.18
public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null) { return null; } ListNode dummy = new ListNode(0); dummy.next = head; head = dummy; while(head.next != null && head.next.next != null) { if(head.next.val == head.next.next.val) { int val = head.next.val; while (head.next != null && head.next.val == val) { head.next = head.next.next; } } else { head = head.next; } } return dummy.next; } }
Reference:
1. http://www.programcreek.com/2014/06/leetcode-remove-duplicates-from-sorted-list-ii-java/