Last active
August 3, 2023 00:22
-
-
Save mvallebr/823d5ab4d05e37bc9a143d2715c820ae to your computer and use it in GitHub Desktop.
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, 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