Skip to content

Commit 58c7450

Browse files
committed
Update Remove Nth Node From End of List.py
avoid use of prev, minimize time complexity
1 parent 629ad80 commit 58c7450

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed
Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
class Solution:
22
def removeNthFromEnd(self, head, n):
3-
fast, slow, prev = head, head, None
4-
while n > 0:
5-
fast, n = fast.next, n - 1
6-
while fast != None:
7-
fast, slow, prev = fast.next, slow.next, slow
8-
if prev == None:
9-
return head.next
10-
prev.next = prev.next.next
11-
return head
3+
dummy = ListNode(-1)
4+
dummy.next = head
5+
left, right = dummy, dummy
6+
while n:
7+
right, n = right.next, n-1
8+
while right.next:
9+
right = right.next
10+
left = left.next
11+
left.next = left.next.next
12+
return dummy.next

0 commit comments

Comments
 (0)