Reputation: 11
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
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