Practice Problem Link: Print Reversed Linked List
Please make sure to try solving the problem yourself before looking at the editorial.
Problem Statement
Given a Linked List, print it in the reverse direction using recursion.
Approach
For every node in the linked list first, print its next node recursively and then print the current node.
Analysis
- Time Complexity:
O(n) - Auxiliary Space Complexity:
O(1)
Implementation
C++
/* This is the ListNode class definition
class ListNode {
public:
int data;
ListNode* next;
ListNode(int data) {
this->data = data;
this->next = NULL;
}
};
*/
void printLinkedListReverse (ListNode* head) {
if(head->next != NULL) {
printLinkedListReverse(head->next);
}
cout << head->data << " ";
return;
}Java
/** This is the ListNode class definition
class ListNode {
int data;
ListNode next;
ListNode(int data) {
this.data = data;
this.next = null;
}
}
**/
class Solution {
void printLinkedListReverse (ListNode head) {
if(head.next != null) {
printLinkedListReverse (head.next);
}
System.out.print(head.data + " ");
return;
}
}