TypechoJoeTheme

IT技术分享

统计

[LeetCode 82] Remove Duplicates from Sorted List II [Java]

2018-03-21
/
0 评论
/
775 阅读
/
正在检测是否收录...
03/21

1. Description

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

2. Example

Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

3. Code

public class LeetCode0082 {

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

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

        ListNode dammy = new ListNode(Integer.MIN_VALUE);
        ListNode current = dammy;
        ListNode pre = head;
        ListNode detect = head.next;

        int duplicate = Integer.MIN_VALUE;

        for (; detect != null; pre = detect, detect = detect.next) {
            if (pre.val == detect.val) {
                duplicate = pre.val;
            } else {
                if (duplicate != Integer.MIN_VALUE) {
                    duplicate = Integer.MIN_VALUE;
                } else {
                    current.next = pre;
                    current = pre;
                }
            }
        }

        if (duplicate == Integer.MIN_VALUE) {
            current.next = pre;
            current = pre;
        }

        current.next = null;
        return dammy.next;
    }
}
Linked
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1482/(转载时请注明本文出处及文章链接)