Delete duplicate-value nodes from a sorted linked list

  • + 0 comments

    My Java solution with o(n) time complexity and o(1) space complexity:

    public static SinglyLinkedListNode removeDuplicates(SinglyLinkedListNode llist) {
            if(llist == null) return llist; //no duplicates to rmv
            
            //use two ptrs to iterate over the linked list
            SinglyLinkedListNode first = llist;
            SinglyLinkedListNode second = llist.next;
            
            while(first != null && second != null){
                //remove the second ptr if its data is equal to the first ptr
                if(first.data == second.data) first.next = second.next;
                //otherwise increase first ptr since data isnt equal
                else first = second;
                
                //increment second ptr to go through entire list
                second = second.next;
            }
            
            return llist;
        }