![]() |
VOOZH | about |
Given a linked list containing N nodes and a positive integer k should be less than or equal to N. The task is to print the last k nodes of the list in reverse order.
Examples:
Input: list: 1->2->3->4->5, k = 2 Output: 5 4 Input: list: 3->10->6->9->12->2->8, k = 4 Output: 8 2 12 9
Source: Amazon Interview Experience SDE Off Campus.
Recursive Approach: Recursively traverse the linked list. When returning from each recursive call keep track of the node number, considering the last node as number 1, second last as number 2 and so on. This counting could be tracked with the help of a global or pointer variable. With the help of this count variable, print the nodes having a node number less than or equal to k.
Below is the implementation of the above approach:
5 4 3 2
Time Complexity: O(n).
Iterative Approach: The idea is to use Stack Data Structure.
Time Complexity: O(n).
Two Pointer Approach The idea is similar to find k-th node from end of linked list.
Time Complexity: O(n).