Java Solution with three pointers


  • 0
    Y

    Move fast pointer n nodes ahead of curr pointer. Also maintain a prev pointer for deletion purpose. If the node to be deleted is the head node, return head.next.

    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            
            if (head.next == null) {
                return null;
            }
            ListNode prev=null;
            ListNode curr=head;
            ListNode fast=head;
            for (int i=1; i<=n; i++) {
                fast = fast.next;
            }
            while (fast != null) {
                prev = curr;
                curr = curr.next;
                fast = fast.next;
            }
            // fast is at the end and curr is nth node from the end
            if (curr == head) {
                return curr.next;
            }
            prev.next = curr.next;
            return head;
            
        }
    }
    

Log in to reply
 

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