82. Remove Duplicates from Sorted List II | Java最短代码实现

原题链接: 82. Remove Duplicates from Sorted List II

【思路】

本题考查链表的基本操作。先新增一个结点dummyHead,其下一个结点指向head,之后发现有重复的,就将该值记录在dup中。循环查找结点值等于dup的,删除即可:

    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;
        ListNode temp = dummyHead;
        while (temp.next != null && temp.next.next != null) {
            if (temp.next.val == temp.next.next.val) {
                int dup = temp.next.val;
                while (temp.next != null && temp.next.val == dup) {
                    temp.next = temp.next.next;
                }
            } else {
                temp = temp.next;
            }
        }
        return dummyHead.next;
    }
166 / 166 test cases passed. Runtime:  2 ms  Your runtime beats 25.85% of javasubmissions.

欢迎优化!

你可能感兴趣的:(list,linked)