Created
December 14, 2018 02:34
-
-
Save jovianlin/bec655af63774e4473b43e69dfe69d44 to your computer and use it in GitHub Desktop.
Remove Nth Node From End of List (in one pass)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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