标签:
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 :
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:
1. http://www.programcreek.com/2014/06/leetcode-remove-duplicates-from-sorted-list-ii-java/
Leetcode Remove Duplicates from Sorted List II
标签:
原文地址:http://www.cnblogs.com/anne-vista/p/4799849.html