Print the last k nodes of the linked list in reverse order | Recursive approach - GeeksforGeeks

07 Jun, 2021
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:  
C++
Java
Python
C#
Javascript
// C++ implementation to print the last k nodes// of linked list in reverse order#include <bits/stdc++.h>using namespace std; // Structure of a nodestruct Node {    int data;    Node* next;}; // Function to get a new nodeNode* getNode(int data){    // allocate space    Node* newNode = new Node;     // put in data    newNode->data = data;    newNode->next = NULL;    return newNode;} // Function to print the last k nodes// of linked list in reverse ordervoid printLastKRev(Node* head,                     int& count, int k){    // if list is empty    if (!head)        return;     // Recursive call with the next node    // of the list    printLastKRev(head->next, count, k);     // Count variable to keep track of    // the last k nodes    count++;     // Print data    if (count <= k)        cout << head->data << " ";} // Driver codeint main(){    // Create list: 1->2->3->4->5    Node* head = getNode(1);    head->next = getNode(2);    head->next->next = getNode(3);    head->next->next->next = getNode(4);    head->next->next->next->next = getNode(5);     int k = 4, count = 0;     // print the last k nodes    printLastKRev(head, count, k);     return 0;}
// Java implementation to print the last k nodes// of linked list in reverse orderclass GfG{ // Structure of a nodestatic class Node{    int data;    Node next;} // Function to get a new nodestatic Node getNode(int data){    // allocate space    Node newNode = new Node();     // put in data    newNode.data = data;    newNode.next = null;    return newNode;} static class C{    int count = 0;} // Function to print the last k nodes// of linked list in reverse orderstatic void printLastKRev(Node head, C c, int k){    // if list is empty    if (head == null)        return;     // Recursive call with the next node    // of the list    printLastKRev(head.next, c, k);     // Count variable to keep track of    // the last k nodes    c.count++;     // Print data    if (c.count <= k)        System.out.print(head.data + " ");} // Driver codepublic static void main(String[] args){    // Create list: 1->2->3->4->5    Node head = getNode(1);    head.next = getNode(2);    head.next.next = getNode(3);    head.next.next.next = getNode(4);    head.next.next.next.next = getNode(5);     int k = 4;    C c = new C();     // print the last k nodes    printLastKRev(head, c, k);}}  // This code is contributed by prerna saini
# Python implementation to print the last k nodes# of linked list in reverse order # Node classclass Node:         # Function to initialise the node object    def __init__(self, data):        self.data = data # Assign data        self.next =None # Function to get a new nodedef getNode(data):     # allocate space    newNode = Node(0)     # put in data    newNode.data = data    newNode.next = None    return newNode class C:    def __init__(self, data):        self.count = data # Function to print the last k nodes# of linked list in reverse orderdef printLastKRev(head, c, k):     # if list is empty    if (head == None):        return     # Recursive call with the next node    # of the list    printLastKRev(head.next, c, k)     # Count variable to keep track of    # the last k nodes    c.count = c.count + 1     # Print data    if (c.count <= k) :        print(head.data, end = " ") # Driver code # Create list: 1->2->3->4->5head = getNode(1)head.next = getNode(2)head.next.next = getNode(3)head.next.next.next = getNode(4)head.next.next.next.next = getNode(5) k = 4c = C(0) # print the last k nodesprintLastKRev(head, c, k) # This code is contributed by Arnab Kundu
// C# implementation to print the last k // nodes of linked list in reverse orderusing System; class GFG{ // Structure of a nodepublic class Node{    public int data;    public Node next;} // Function to get a new nodestatic Node getNode(int data){    // allocate space    Node newNode = new Node();     // put in data    newNode.data = data;    newNode.next = null;    return newNode;} public class C{    public int count = 0;} // Function to print the last k nodes// of linked list in reverse orderstatic void printLastKRev(Node head, C c, int k){    // if list is empty    if (head == null)        return;     // Recursive call with the next    // node of the list    printLastKRev(head.next, c, k);     // Count variable to keep track     // of the last k nodes    c.count++;     // Print data    if (c.count <= k)        Console.Write(head.data + " ");} // Driver codepublic static void Main(String []args){         // Create list: 1->2->3->4->5    Node head = getNode(1);    head.next = getNode(2);    head.next.next = getNode(3);    head.next.next.next = getNode(4);    head.next.next.next.next = getNode(5);     int k = 4;    C c = new C();     // print the last k nodes    printLastKRev(head, c, k);}} // This code is contributed by Arnab Kundu
<script> // Javascript implementation of the approach // Structure of a nodeclass Node {        constructor() {                this.data = 0;                this.next = null;             }        }                  // Function to get a new nodefunction getNode( data){    // allocate space    var newNode = new Node();     // put in data    newNode.data = data;    newNode.next = null;    return newNode;}  class C{constructor() {    this.count = 0;    }} // Function to print the last k nodes// of linked list in reverse orderfunction printLastKRev( head,  c,  k){    // if list is empty    if (head == null)        return;     // Recursive call with the next node    // of the list    printLastKRev(head.next, c, k);     // Count variable to keep track of    // the last k nodes    c.count++;     // Print data    if (c.count <= k)        document.write(head.data + " ");} // Driver Code // Create list: 1->2->3->4->5var head = getNode(1);head.next = getNode(2);head.next.next = getNode(3);head.next.next.next = getNode(4);head.next.next.next.next = getNode(5); let k = 4;let c = new C(); // print the last k nodesprintLastKRev(head, c, k); // This code is contributed by jana_sayantan.</script>
5 4 3 2
 
Time Complexity: O(n).Iterative Approach: The idea is to use Stack Data Structure.  
Push all linked list nodes to a stack.Pop k nodes from stack and print them.
Push all linked list nodes to a stack.
Pop k nodes from stack and print them.
Time Complexity: O(n).Two Pointer Approach The idea is similar to find k-th node from end of linked list.  
Move first pointer k nodes ahead.Now start another pointer, second from head.When first pointer reaches end, second pointer points to k-th node.Finally using the second pointer, print last k nodes.
Move first pointer k nodes ahead.
Now start another pointer, second from head.
When first pointer reaches end, second pointer points to k-th node.
Finally using the second pointer, print last k nodes.
Time Complexity: O(n). 
prerna saini
andrew1234
Harsha987
jana_sayantan
Amazon
Linked List
Recursion
Stack
Amazon
Linked List
Recursion
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LinkedList in Java
Linked List vs Array
Doubly Linked List | Set 1 (Introduction and Insertion)
Merge two sorted linked lists
Detect loop in a linked list
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction