No Extra Spaces, O(n) solution with two pointers


  • -1
    A
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if(head == null)
                return null;
            ListNode sen = new ListNode(-1);
            sen.next = head;
            ListNode ptr1 = sen;
            ListNode ptr2 = head;
            while(ptr1!= null)
            {
                while(ptr2!=null && ptr2.next!=null && ptr2.next.val == ptr2.val)
                {
                    while(ptr2.next!=null && ptr2.next.val == ptr2.val)
                    {
                        ptr2 = ptr2.next;
                    }
                    ptr2 = ptr2.next;    
                }
                ptr1.next = ptr2;
                ptr1 = ptr2;
                if(ptr2 != null)
                    ptr2 = ptr2.next;
            }
            return sen.next;
        }
    }

Log in to reply
 

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