Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinctnumbers from the original list.

For example,
Given1->2->3->3->4->4->5, return1->2->5.
Given1->1->1->2->3, return2->3.

Solution: 注意与Array Deduplication III的比较。

    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(0), fast1 = head, slow = dummy;
        int count = 1;
        for (ListNode fast2 = head.next; fast2 != null; fast2 = fast2.next) {
            if (fast2.val == fast1.val) {
                count++;
                continue;
            }
            //用count == 1表示fast2 - fast1 == 1
            if (count == 1) {
                slow.next = fast1;
                slow = slow.next;
            }
            fast1 = fast2;
            count = 1;
        }
        //记得有这步,补上最后一个fast1,或者slow.next置null
        if (fast1.next == null) {
            slow.next = fast1;
        } else {
            slow.next = null;
        }
        return dummy.next;
    }

results matching ""

    No results matching ""