Remove duplicates from sorted linkedlist II using Java


  • 0
    J

    Below is solution in Java

    class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            
            ListNode current = head;
            ListNode dummy = null;
            ListNode FakeHead = new ListNode(0);
            ListNode prev = FakeHead;
            FakeHead.next = head;
            if(head == null || head.next == null) return head;
            while(current!=null && current.next!=null){
                if(current.val == current.next.val)
                   {
                         dummy = current;
                    
                      while(dummy!=null && dummy.val == current.val)
                        {
                                dummy = dummy.next;
                                         
                        }
                                
                       if(dummy == null) 
                       {
                           prev.next = null;
                           return FakeHead.next;
                       }
                        if(dummy != null)
                        {
                            current = dummy;
                            prev.next = current;
                           
                        }
                }
                else
                {
                    prev = current;
                    current = current.next;
                }
            }
            return FakeHead.next;
        }
    }
    

Log in to reply
 

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