Given A linked list, remove the nth node from the end of the list and return its head.
For example,
Given linked list:1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n would always be valid.
Try to do the in one pass.
The most direct idea of this topic is to go through the whole list to know the length, and then go to the total length minus the point you want to get the position to skip. This requires walking both sides with a pointer time complexity of O (2n)
L Another way of thinking is to use two pointers fast and slow. Fast first step n, slow this time to start from the beginning, when fast came to the end of the slow will go to need to skip the position.
That's all it takes to go through.
Intuitively, the first idea we have are to iteratively go through the whole list and then count the length of the list. Then we deduct the required spot from the end. The result is the length of we need to go from the beginning.
Say the whole length is L we want to delete n from the end. We need to go l-n from the begining.
This method would require us to go through the whole list for twice. The time complexity is O (2n) and require one pointer.
Another method would require and pointers. Fast and Slow.
1. Fast go n steps from the beginning.
2. Slow start from the beginning.
3. When fast goes to the end of the list slow goes to the spot we want to delete.
Code is as follow:
# Definition for singly-linked list.# class listnode:# def __init__ (self, x): # self.val = x# Self.next = Nonec Lass Solution: # @return a listnode def removenthfromend (self, head, N): dummy=listnode (0) Dummy.next =head fast=dummy slow=dummy while n>0: fast=fast.next n-=1 while fast.next: Fast=fast.next slow=slow.next slow.next=slow.next.next return Dummy.next
Remove Nth Node from End of List Leetcode Python