My straightforward java solution


  • 0
    X
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if(head==null|| head.next==null) return head;
            
            ListNode prepre=null;
            ListNode pre=head;
            ListNode node=pre.next;
            
            while(node!=null){
                if(node.val==pre.val){
                    if(prepre==null){
                         while(node.next!=null && node.next.val==node.val){
                            node=node.next;
                        }
                        head=node.next;
                        if(head==null) break;
                        node=head.next;
                        pre=head;
                        prepre=null;
                    }
                    else{
                        while(node.next!=null && node.next.val==node.val){
                            node=node.next;
                        }
                       prepre.next=node.next;
                       if(node.next==null) return head;
                       pre=prepre.next;
                       node=pre.next;
                    }
                }
                else{
                    prepre=pre;
                    pre=node;
                    node=node.next;
                }
            }
            return head;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.