I am trying to print the value of a linked list in reverse order using recursion. Here is the code:
#include <iostream>
// Node structure
struct node{
int data;
struct node* next;
node(int val){
data = val;
next = NULL;
}
};
void print_in_reverse(struct node* head){
if(head == NULL){
return;
}
print_in_reverse(head->next);
std::cout<<"Node value "<<head->data<<"\n";
}
int main() {
// Make a test linked list
// 2->4->6->9->NULL
struct node* head = new node(2);
head->next = new node(4);
head->next->next = new node(6);
head->next->next->next = new node(9);
print_in_reverse(head);
return 0;
}
It does the job pretty well. However, I am a little confused about the time complexity. Iterating over the linked list using recursion is O(n), I get it. But, do we also consider the time when the recursion visit the nodes again to finish the unfinished recursive state before they pop out of the stack memory? The question is: Is the time complexity of the algorithm, O(n), or O(n) + O(n)?