82. Remove Duplicates from Sorted List II

Description

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.

Solution

Two-pointers

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode tail = dummy;
        ListNode curr = head;
        
        while (curr != null) {
            int count = 1;
            curr = curr.next;
            
            while (curr != null && curr.val == tail.next.val) {
                ++count;
                curr = curr.next;
            }
            
            if (count == 1) {   // only 1 node between tail and curr
                tail = tail.next;
            } else {    // discard nodes between tail and curr
                tail.next = curr;
            }
        }
        
        return dummy.next;
    }
}

你可能感兴趣的:(82. Remove Duplicates from Sorted List II)