Tolani Jaiye-Tikolo - 1 year ago 69
C++ Question

# print Linked List elements using recursion

I was solving the Print in reverse challenge on Hackerrank

The
`void ReversePrint(Node* head)`
any input from stdin/console. The head may be empty so nothing should be printed. Print the elements of the linked list in reverse order to
stdout/console (using printf or cout) , one per line.

Sample Input

1 --> 2 --> NULL

2 --> 1 --> 4 --> 5 --> NULL

Sample Output

``````2
1
5
4
1
2
``````

I solved it using this

``````    #include <vector>
{
// This is a "method-only" submission.
// You only need to complete this method.

std::vector<int> nodeList;

}

for (std::vector<int>::iterator it = nodeList.end()-1 ; it != nodeList.begin()-1; --it){
std::cout << *it <<endl;
}
}

}
``````

It works perfectly but extending to use recursion provides the wrong answer, why is this happening?

``````std::vector<int> nodeList;
}
else{
for (std::vector<int>::iterator it = nodeList.end()-1 ; it != nodeList.begin()-1; --it){
std::cout << *it <<endl;
}

}

}
``````

the result is

``````2
1
5
4
1
2
2
1
``````

NB: The structure of the Node is given as
struct Node
{
int data;
struct Node *next;
}

Why so complicated?

``````/* Function to reverse print the linked list */