82.Remove Duplicates from Sorted List II (M)

1.Description(Medium)

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

Example

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

2.Code

https://www.jiuzhang.com/solutions/remove-duplicates-from-sorted-list-ii/

此题与112相比,有可能会换head,所以要用dummy来做。而且要一次性删完所有的重复值。

 public static ListNode deleteDuplicates(ListNode head) {
        if(head==null){
            return null;
        }

        ListNode dummy=new ListNode(0);
        dummy.next=head;
        ListNode prev=dummy;

        while(prev.next!=null && prev.next.next!=null){

            if(prev.next.val==prev.next.next.val){
                //要一次性删完
                int value=prev.next.val;
                while(prev.next!=null && prev.next.val==value){
                    prev.next=prev.next.next;
                }
            }
            else{
                prev=prev.next;
            }          
        }

        return dummy.next;
    }

Last updated