Java iterative solution


  • 0
    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;
        ListNode prev = dummyHead;
        ListNode current = head;
        while (current != null) {
            if (current.next != null && current.next.val == current.val) {
                int dupVal = current.val;
                while ( current != null && current.val == dupVal) {
                    current = current.next;
                }
            }
            else {
                prev.next = current;
                prev = current;
                current = current.next;
            }
        }
        prev.next = null;
        return dummyHead.next;
    }

Log in to reply
 

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