56
loading...
This website collects cookies to deliver better user experience
LinkedList
Data structure.head
of a linked list, remove the nth
node from the end of the list and return its head.sz
.1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
💡 Give yourself atleast 15-20 mins to figure out the solution :)
L - n + 1
th node where L
is the length of list.m
distance from the start, you'll end being on the m + 1
th node.start
) at the start of linkedlist, we can reach the m
th node in original linkedlist in m
steps from start
. ( 1 step means cur = cur→next
operation )📓 This approach might look a bit complicated but believe me, it is VERY important to understand it as this method forms the basis of many other questions( important ones ) on linkedlist.
L - n + 1
th node from the beginning.fast
and slow
equal to start
node i.e their next
is equal to head
.fast
point to the n
th node in original linkedlist by peforming n
iterations( steps ).fast
to reach the last node?n
th node from start, so after L - n
steps we will reach the last node. [IMP]fast
and slow
simultaneouly one step at a time untill fast
reaches the last node. This will ensure both pointers perform L - n
steps.slow
points to the L - n
th node. ( Point 2 of buldingblocks )slow → next
) using slow
pointer.//Definition for singly-linked list.
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
ListNode *removeNthFromEnd(ListNode *head, int n)
{
//! list is never empty
//- initializing pointers
ListNode *start = new ListNode();
start->next = head;
ListNode *fast = start;
ListNode *slow = start;
//make fast point to the nth node
for (int i = 1; i <= n; i++)
{
fast = fast->next;
}
//move "slow" ahead untill "fast" points to the last node
//i.e point "slow" to one node preceding the required node
while (fast->next != nullptr)
{
fast = fast->next;
slow = slow->next;
}
//deleting the nth node from end or n-k+1th node from begin
ListNode *t = slow->next;
slow->next = slow->next->next;
delete t;
return start->next;
}
L
is the length of linkedlist here