Skip to content

Instantly share code, notes, and snippets.

@jovianlin
Created December 14, 2018 02:34
Show Gist options
  • Save jovianlin/bec655af63774e4473b43e69dfe69d44 to your computer and use it in GitHub Desktop.
Save jovianlin/bec655af63774e4473b43e69dfe69d44 to your computer and use it in GitHub Desktop.
Remove Nth Node From End of List (in one pass)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
to_return, future = head, head
for _ in range(k):
future = future.next
prev = None
while future is not None:
prev = head
head = head.next
future = future.next
if prev is None:
return head.next
else:
prev.next = head.next
del head
return to_return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment