Simple Java Solution


  • 0

    We can compare a node with its descendants. There are 2 conditions:

    1. it's unique. we just move the Pre pointer forward
    2. Find all duplicates and remove all of them.
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if(head == null || head.next ==null)
                return head;
            ListNode fakeHead = new ListNode(9);
            fakeHead.next = head;
            ListNode pre = fakeHead;
            while(pre.next!=null){
                ListNode cur = pre.next;
                ListNode dup = cur;
                while(dup.next!=null && dup.next.val==dup.val){
                    dup = dup.next;
                } 
                if(cur!=dup){   // condition 2.
                    pre.next = dup.next;
                }else{  // condition 1
                    pre = pre.next;
                }
            }
            
            return fakeHead.next;
        }
    }
    

Log in to reply
 

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