Easy Java two pointers solution


  • 0
    C

    The basic idea is having a fast pointer that walks n steps from the head, and when fast.next == null we know slow.next is the nth element.

       ListNode fast = head, slow = head;
        if(head == null){
            return null;
        }
        while(n != 0){       //walking n times forwrad
            fast = fast.next;
            n--;
        }
        if(fast == null ){    //if after initial walk fast == null, we know the nth element is the head
            return head.next;
        }
        while(fast.next != null){ 
            slow = slow.next;
            fast = fast.next;
        }
        slow.next = slow.next.next; // remove the n the node
        return head;

Log in to reply
 

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