File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Remove Nth Node From End of List
2+ # https://leetcode.com/problems/remove-nth-node-from-end-of-list/
3+
4+ # Definition for singly-linked list.
5+ # class ListNode(object):
6+ # def __init__(self, val=0, next=None):
7+ # self.val = val
8+ # self.next = next
9+ class Solution (object ):
10+ def removeNthFromEnd (self , head , n ):
11+ # we assign fast pointer rabbit to head
12+ rabbit = head
13+ # since head node is counted as 1, we stop when n = 1
14+ while (n > 1 ):
15+ # we want to advance rabbit to n nodes
16+ rabbit = rabbit .next
17+ n = n - 1
18+ # we assign slow pointer tortoise to head
19+ tortoise = head
20+ # we also need previous pointer to concatinate the singly linked list
21+ prevPtr = head
22+ # move both rabbit and tortoise unitl rabbit reaches the end
23+ while (rabbit .next ):
24+ prevPtr = tortoise
25+ rabbit = rabbit .next
26+ tortoise = tortoise .next
27+ # now tortoise is at the n th to last node.
28+ # if we have to remove head, just advance the head to it's next value, even if that value is null.
29+ if (tortoise == head ):
30+ head = head .next
31+ else :
32+ # we remove tortoise with help of prev pointer
33+ prevPtr .next = tortoise .next
34+ return head
35+ """
36+ :type head: ListNode
37+ :type n: int
38+ :rtype: ListNode
39+ """
40+
Original file line number Diff line number Diff line change 180180 <p><b>Approach</b>: Use heap sort to merge k lists.
181181 </p>
182182 </li>
183- <li>Remove Nth Node From End Of List</li>
183+ <li><a href="Programs/Remove Nth Node From End of List.py">Remove Nth Node From End Of List</a>
184+ <p><b>Approach</b>: Use rabbit and tortoise method. Move rabbit n spaces, then move tortoise along with rabbit unitl rabbit reaches end of the list.
185+ </p>
186+ </li>
184187 <li>Reorder List</li>
185188 </ul>
186189 <h2 >Matrix</h2 >
You can’t perform that action at this time.
0 commit comments