- uses p1 to move n steps
- uses p2 to catch p1 util p1 arrives the end of the list
Complexity T : O(N) M : O(1)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
p1 = head
p2 = head
i = 0
p1 = p1.next
while p1.next != None:
p1 = p1.next
i = i + 1
if i == n - 1:
for i in range(n):
p1 = p1.next
p2 = head
if not p1:
return p2.next
while p1.next != None:
p1 = p1.next
p2 = p2.next
if p2.next.next:
p2.next = p2.next.next
else:
p2.next = None
return head