Skip to content

Instantly share code, notes, and snippets.

@mvallebr
Last active August 3, 2023 00:22
Show Gist options
  • Save mvallebr/823d5ab4d05e37bc9a143d2715c820ae to your computer and use it in GitHub Desktop.
Save mvallebr/823d5ab4d05e37bc9a143d2715c820ae to your computer and use it in GitHub Desktop.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
current, nth = head, ListNode(val=None, next=head)
while current:
current = current.next
if n > 0:
n -= 1
else:
# only advance nth after the sub list has nth elements
nth = nth.next
if nth.val is None:
# head is the next element
return head.next
else:
nth.next = nth.next.next if nth.next else None
return head
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment