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.

 

public ListNode deleteDuplicates(ListNode head) {
    ListNode dummy = new ListNode(0);
    ListNode node = dummy;
    while(head != null) {
        ListNode p = head;
        while(head.next != null && head.val == head.next.val) {
            head = head.next;
        }
        if(p == head) {
            node = node.next = p;
        }
        head = head.next;
    }
    node.next = null;
    return dummy.next;
}

 

你可能感兴趣的:(LeetCode)