Leetcode 82 - 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.
Example1:

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

Example2:

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


思路:

首先创建一个结点命名为Node。指向head结点。之后设置两个结点previousnext。previous指向Node结点,next指向Node.next结点。之后进行循环,首先判断previous的值和next的值是否相同。

如果相同则循环next结点。循环条件是看next结点的值和next.next结点的值是否相同以及next.next是否为null。next.next为null的时候说明一直到结尾都有重复的数值,此时previous.next直接指向null。不为null的情况说明next.next和previous之间都是重复的值。此时修改previous和next结点。previous.next指向next.next,next指向next.next。

如果不同,则将previous结点指向next结点,next结点指向next.next结点。


代码:

public ListNode deleteDuplicates(ListNode head) {
        if(head == null)
            return null;
        ListNode node = new ListNode(0);
        node.next = head;
        ListNode previous = node;
        ListNode next = node.next;
        while(next.next != null){
            if(next.val == next.next.val){
                while(next.next != null && next.val == next.next.val){
                    next = next.next;
                }
                if(next.next == null){
                    previous.next = null;
                    break;
                }
                previous.next = next.next;
                next = next.next;
            }else{
                previous = next;
                next = next.next;
            }
        }
        return node.next;
}

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