0082. Remove Duplicates From Sorted List Ii

82. Remove Duplicates from Sorted List II #

题目 #

给定排序链表的头节点head,删除原始链表中所有重复数字的节点,只留下不同的数字。返回已排序的链表。

链表数据保证链表已经按升序排列。

思路 #

代码 #

public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode sentinel = new ListNode(-1, null);
        ListNode preserve = sentinel, anchor = head;
        while (anchor != null) {
            ListNode probe = anchor.next;
            if (probe == null || probe.val != anchor.val) {
                preserve.next = anchor;
                preserve = anchor;
                preserve.next = null;
            }
            else while (probe != null && probe.val == anchor.val) probe = probe.next;
            anchor = probe;
        }
        return sentinel.next;
    }
}