Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Method 1:find length then do len-n and print (len-n)th node
- T.C O(n) but two pass S.C O(1)
- Mthod 2:use recursion T.C O(n), S.C O(n) due to stack of recursion calls
- Method 3: use two pointers
- first make two pointer.keep first pointer at head and
- move second pointer to nth node.Now first pointer is
- nth left of second pointer.now move both pointer one
- step at a time until second reaches at end.
- still first pointer will be nth left of second pointer
- and end of linkedlist also.
- T.C O(n) two pass but one pass is not full linked list,S.C O(1)
- */
- fast = head
- slow = head
- # Move fast n steps ahead
- for _ in range(n):
- fast = fast.next
- # If fast is None, that means we need to remove the head
- if not fast:
- return head.next
- # Move both pointers until fast reaches the last node
- while fast.next:
- slow = slow.next
- fast = fast.next
- # Remove the target node
- slow.next = slow.next.next
- return head
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement