Skip to content

Instantly share code, notes, and snippets.

@ericness
Created March 27, 2022 02:00
Show Gist options
  • Save ericness/761941876a8fe121a914fb0448f96b29 to your computer and use it in GitHub Desktop.
Save ericness/761941876a8fe121a914fb0448f96b29 to your computer and use it in GitHub Desktop.
LeetCode 19 two pointer solution
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
"""
dummy = ListNode(0, head)
left = dummy
right = head
node_index = 0
while node_index < n:
right = right.next
node_index += 1
while right:
right = right.next
left = left.next
left.next = left.next.next
return dummy.next
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment