82. Remove Duplicates from Sorted List II (Medium)

https://leetcode.com/problems/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.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
Output: 2->3

Solutions

class Solution {

    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        // The list at least contains 2 elements

        ListNode preHead = new ListNode(-1);
        preHead.next = head;
        // pre->1->1->1

        // p1->p2->p3
        ListNode p1 = preHead;
        ListNode p2 = p1.next;
        ListNode p3 = p2.next;

        while (p3 != null) {
            // 1->2->3
            if ((p2.val != p3.val)) {
                p1 = p2;
                p2 = p1.next;
                p3 = p2.next;

                continue;
            }

            // 1->2->2->3
            while (p3 != null && p2.val == p3.val) {
                p2 = p2.next;
                p3 = p2.next;
            }

            p1.next = p3;
            p2 = p1.next;
            if (p2 != null) {
                p3 = p2.next;
            }
        }

        return preHead.next;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-03 11:01:18

results matching ""

    No results matching ""