Skip to content

Instantly share code, notes, and snippets.

@Khamies
Created March 28, 2023 03:32
Show Gist options
  • Save Khamies/3eb69c894d1c40a13d284dd75949a084 to your computer and use it in GitHub Desktop.
Save Khamies/3eb69c894d1c40a13d284dd75949a084 to your computer and use it in GitHub Desktop.
def remove_nth_node(head, n):
i_slow = head
j_fast = head
# first we will move the fast pointer so that the distance between
# j_fast - j_slow = n
for _ in range(n):
j_fast = j_fast.next
if not j_fast: # return the next node to the slow pointer, if the
# the number of nodes are less than n.
return i_slow.next
while j_fast.next:
j_fast = j_fast.next
i_slow = i_slow.next
i_slow.next = i_slow.next.next
return head
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment