Very straightforward java solution


  • 0
    L

    //use a counter to keep track of duplicate nodes. Reset the counter when run into a new node. If counter == 1 , add current node, else skip to next node.

    public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode dum = new ListNode(0);
        ListNode cur =  head, cur0 = dum;
        int cnt = 1;
        while(cur.next != null){
            if(cur.val == cur.next.val){ // if current node the same as next node , keep going
                cnt++;
            } else if(cnt == 1) { // if not, check if current node is duplicate
                cur0.next = cur;
                cur0 = cur0.next;
                cnt = 1;
            } else {
                cnt = 1;
            }
            cur = cur.next;
            //take care of last node. 
            if(cur.next == null){
                if(cnt == 1) cur0.next = cur; 
                else cur0.next = null;
            }
        }
        
        return dum.next;
        
        
    }

Log in to reply
 

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