题目
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
.
由于头结点也可能被操作,所以加个哨兵可以简化代码。细心即可。
代码
public class RemoveDuplicatesFromSortedListII { public ListNode deleteDuplicates(ListNode head) { if (head == null) { return head; } ListNode dummy = new ListNode(0); dummy.next = head; ListNode p = dummy; ListNode q = head; ListNode t = q.next; while (t != null) { if (t.val != q.val) { if (q.next == t) { p = q; } else { p.next = t; } q = t; } t = t.next; } if (q.next != null) { p.next = null; } return dummy.next; } }
LeetCode | Remove Duplicates from Sorted List II,布布扣,bubuko.com
LeetCode | Remove Duplicates from Sorted List II
原文:http://blog.csdn.net/perfect8886/article/details/21319021