My iterative solution in Java


  • 0

    Have a look at my iterative solution in Java using fast and slow pointers. Please, share your thoughts about any optimizations. Thank you.

    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode focusNode = dummy;
        while (focusNode.next != null && focusNode.next.next != null) {
            ListNode slow = focusNode.next;
            ListNode fast = focusNode.next.next;
            if (slow.val != fast.val) {
                focusNode = focusNode.next;
            } else {
                int val = slow.val;
                while (slow != null && val == slow.val) {
                    slow = slow.next;
                }
                focusNode.next = slow;
            }
        }
        return dummy.next;
    }

Log in to reply
 

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