Java concise solution without dummy node O(n) time, O(1) Space


  • 0
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            ListNode newHeader = null;
            ListNode newTailer = null;
            ListNode prev = null;
            ListNode cur = head;
            while(cur != null){
                //check whether the current node is equal to next or previous node
                if(cur.next != null && cur.val == cur.next.val || prev != null && prev.val == cur.val ){
                    prev=cur;
                    cur=cur.next;
                    continue;
                }
                
                //first node in the distinct list
                if(newTailer == null){
                    newHeader=cur;
                    newTailer=cur;
                }
    ​            //append to the end of the new list
                else{
                    newTailer.next=cur;
                    newTailer=cur;
                }
                prev =cur;
                cur=cur.next;
            }
            if(newTailer == null) return null;
    
            //set the next node of tailer to be null, trimming the nodes after the tailer
            newTailer.next=null;
            return newHeader;
        }
    }
    

Log in to reply
 

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