ctci/02. Linked lists/remove_ntg_node_from_tail.py

14 lines
431 B
Python

# https://leetcode.com/problems/remove-nth-node-from-end-of-list/discuss/8802/3-short-Python-solutions
class Solution:
def removeNthFromEnd(self, head, n):
slow = fast = head
for _ in range(n):
fast = fast.next
if not fast:
return head.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return head