Skip to content

Instantly share code, notes, and snippets.

@RobGThai
Created October 21, 2021 11:46
Show Gist options
  • Save RobGThai/f85478cfb6bbbd1eb531b09c17e6ac5a to your computer and use it in GitHub Desktop.
Save RobGThai/f85478cfb6bbbd1eb531b09c17e6ac5a to your computer and use it in GitHub Desktop.

Revisions

  1. RobGThai created this gist Oct 21, 2021.
    33 changes: 33 additions & 0 deletions removeN.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    # 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