Skip to content

Commit

Permalink
Update Remove Nth Node From End of List.py
Browse files Browse the repository at this point in the history
avoid use of prev, minimize time complexity
  • Loading branch information
resorcap committed Mar 8, 2015
1 parent 629ad80 commit 58c7450
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions Remove Nth Node From End of List.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
class Solution:
def removeNthFromEnd(self, head, n):
fast, slow, prev = head, head, None
while n > 0:
fast, n = fast.next, n - 1
while fast != None:
fast, slow, prev = fast.next, slow.next, slow
if prev == None:
return head.next
prev.next = prev.next.next
return head
dummy = ListNode(-1)
dummy.next = head
left, right = dummy, dummy
while n:
right, n = right.next, n-1
while right.next:
right = right.next
left = left.next
left.next = left.next.next
return dummy.next

0 comments on commit 58c7450

Please sign in to comment.