Simple Java solution with comments


  • 0
    C
    public ListNode deleteDuplicates(ListNode head) {
            ListNode dummy = new ListNode(0), p = dummy;
            while(head != null) {
                int val = head.val;
                if (head.next != null && head.next.val == val) {// if we have duplicates in pair of values
                    head = head.next; //get on last duplicate in pair of values
                    while(head != null && head.val == val) head = head.next; // iteratively we get the next value
                }
                else {
                    p.next = head; // head points to unique value
                    p = p.next;
                    head = head.next;
                }
            }
            p.next = null; //cut off the chain of nodes within original linked list
            return dummy.next;
        }

Log in to reply
 

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