Nihal Pandey
Nihal Pandey

Reputation: 11

Leetcode - Remove Nth Node From End of List

Given the head of a linked list, remove the nth node from the end of the list and return its head.

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode ptr1=head, ptr2=head;
        for(int  i =0;i<n;i++)
            ptr2=ptr2.next;
        
        while(ptr2.next!=null){
            ptr1=ptr1.next;
            ptr1=ptr2.next;
        }

        ptr1.val = ptr1.next.val;
        ptr1.next = ptr1.next.next;
        return head;
    }
}

I am getting "Time limit exceeded" here for some reason. Can anybody help?

Upvotes: 1

Views: 120

Answers (1)

Abhinav Mathur
Abhinav Mathur

Reputation: 8111

The TLE verdict is due to a typo in your program:

while(ptr2.next!=null){
    ptr1=ptr1.next;
    ptr1=ptr2.next;
}

You're not moving ptr2, so while (ptr2.next != null) iterates indefinitely. This fix should remove the TLE verdict:

while(ptr2.next!=null){
    ptr1=ptr1.next;
    ptr2=ptr2.next;
}

Upvotes: 1

Related Questions