Created
March 24, 2022 22:43
-
-
Save ericness/29fe906bee0f7792681262c40cc27320 to your computer and use it in GitHub Desktop.
LeetCode 19 Two Pass attempt 1
This file contains hidden or 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
from typing import Optional | |
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]: | |
"""Remove the nth from the last node. | |
Args: | |
head (Optional[ListNode]): Head of list | |
n (int): Node to remove | |
Returns: | |
Optional[ListNode]: Modified list | |
""" | |
length = 0 | |
current = head | |
while current: | |
current = current.next | |
length += 1 | |
node_to_remove = length - n | |
current = head | |
for _ in range(node_to_remove - 1): | |
current = current.next | |
if current.next: | |
current.next = current.next.next | |
else: | |
current.next = None | |
return head |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment