Created
October 21, 2021 11:46
-
-
Save RobGThai/f85478cfb6bbbd1eb531b09c17e6ac5a to your computer and use it in GitHub Desktop.
LinkedList solution.
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]: | |
if not head.next: | |
# Single node input meaning n = 1 | |
return None | |
print(f"Nth node: {n}") | |
col = [] | |
idx = 0 | |
node = head | |
while node: | |
if len(col) == n + 1: | |
col = col[1:] | |
col += [node] | |
node = node.next | |
s = len(col) | |
if n > 1 and n < s: | |
col[0].next = col[2] # Normal case | |
elif n == 1: | |
col[-2].next = None # Drop last | |
elif n == s: | |
head = col[1] # Drop first | |
return head |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment