We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
It worked. but it is bit confusing since there is already a "printSinglyLinkedList(...)" function so I was assuming we need to use this function to print elements.
void ReversePrint(Node *head)
{
// This is a "method-only" submission.
// You only need to complete this method.
if(head){
ReversePrint(head->next);
printf("%d\n",head->data);
}
}
My only conern with this is that a LinkedList could be quite long, and the recursion depth limit is usually only around 5000, which really isn't that deep.
I took sophist_pt's code and altered it a bit to hopefully make it more intuitive.
void ReversePrint(Node head) {
//if the head is not yet null...
if (head != null) {
//call the function again but on the next node
ReversePrint(head.next);
/*----------------------------------------------
The recursion will get "stacked" right here!
The code below this area will not get called
until we go back up through the recursive stack.
-----------------------------------------------*/
System.out.println(head.data);
}
}
Here's a code trace for an example.
We have a linked list of three elements [1] -> [2] -> [3] Let's begin by calling the head.
A. RevPr(1)
if elemenent 1 is not yet null, move on.
It's not null! Call again on next, element 2...
B. RevPr(2)
if elemenent 2 is not yet null, move on.
It's not null! Call again on next, element
3...
C. RevPr(3)
if elemenent 3 is not yet null,
move on. It's not null! Call again
on next, element 4...
D. RevPr(4)
if elemenent 4 is not yet null, move on.
Wait, it is null! No more calls, we're done.
So we just built this recursive stack.
[RevPr1(RevPr2(RevPr3(RevPr4)))]
Now we have to execute the function that is innermost. Why? Because that's where we were most recently!
D. RevPr4. That most recent call failed the
condition. Nothing is printed.
-->[RevPr1(RevPr2(RevPr3()))]
C. RevPr3. RevPr3 never finished the code in
the if statement, so now we print 3!
-->3
-->[RevPr1(RevPr2())]
B. RevPr2. Now we need to print 2!
-->3
-->2
-->[RevPr1()]
A. RevPr1. The last call! Print 1! This call is done, and
now everything is done.
-->3
-->2
-->1
This function was written from sophist_pt's brilliant code.
My pleasure! Recursion hurts my brain too... But eventually with enough practice one is able to understand when and how recursion is useful. (Hopefully without spending a half-hour to trace the process out like I did.)
void ReversePrint(Node *head)
{
// This is a "method-only" submission.
// You only need to complete this method.
if(head){
ReversePrint(head->next);
printf("%d\n",head->data);
}
}
This comment will probably get burried, but basically...if i understood this correctly, the last one who calls and enters the if (head != null) get's to do the print statement first.
Then it unravells until the first one who called the if statements get's their turn to print it out.
Excellent explanation! sophist_pt's answer (and the other recursion answers) confused me. From reading yours I understood it and realized I need some more work on recursion! Thanks!
does recursion allow as to move one step backward
i dont no why you say that we just built this recursive stack. [RevPr1(RevPr2(RevPr3(RevPr4)))]
in which line does it mean that
and if it is a stsck so we moves backward why does it read the only last code (print (head.data))
i am sorry if i didnot explain my problem in easy way so you can understand me as i am a beginner
thanks for your explanation
void ReversePrint(Node *head)
{
// This is a "method-only" submission.
// You only need to complete this method.
if(head){
ReversePrint(head->next);
printf("%d\n",head->data);
}
}
I got this runtime exception as well. For me, it was for the Test Case #1 where they have an input of just 0 for one of there queries. Normally, it is a number for the # of nodes in the linked list followed by a set of numbers that need to be reversely printed.
You can test it out by using custom input of the Test Case #1 input and removing the 0 from the input data and changing the first 5 to 4 queries after.
Yeah. Recursive solutions generally don't work well when n is very big because of the demands on the stack. Classic example is computing the Fibonacci numbers. Compare the recurisve solution against the iterative one.
Yes, I agree and this can be an important consideration for large data sets or relatively large data sets on platforms with restricted stack sizes. If Hackerrank doesn't already, I think they could include variations on problems like this that enforce iterative solutions.
This immediately came to mind for me. It might look really nice, and really neat, but you would never do this in reality. You run the risk of overflowing the stack.
It's through recursion,
ex : 1->4->8->9
In this first the head will move till head is NULL
and then returns control to the previous call
then printing of the last ele is done
then the control is returned to the previous call
then printing of the last second ele and so on.
Because you are first putting it as head.next which means if it IS null, it will already be at head.next and the return will basically return to the pre-recursion of the last function just to get print a null value
What his code does is, if head.next is null, it will return so that head.data will be printed, otherwise, head=head.next will happen and that will be put into the same function
By calling the function recursively before the print statement, you first get to the end of the linked list and print the final value, print the last but 1 value, etc until you print the first value.
I could never think of such a short and neat approach.
here is my bruteForce method:-
static void reversePrint(SinglyLinkedListNode head) {
ArrayList<Integer> pl=new ArrayList();
SinglyLinkedListNode temp=head;
while(temp!=null){
pl.add(temp.data);
temp=temp.next;
}
Collections.reverse(pl);
for(int i:pl){
System.out.println(i);
}
Print in Reverse
You are viewing a single comment's thread. Return to all comments →
You could do it recursively which is a lot neater. The code below is in Java.
void ReversePrint(Node head) {
}
Recursion never felt so good :D
That conditional is a bit ugly, why not
nice
here is problem solution in python java c++ and c programming. https://solution.programmingoneonone.com/2020/07/hackerrank-print-in-reverse-solution.html
It worked. but it is bit confusing since there is already a "printSinglyLinkedList(...)" function so I was assuming we need to use this function to print elements.
here is problem solution in python java c++ and c programming. https://solution.programmingoneonone.com/2020/07/hackerrank-print-in-reverse-solution.html
Even shorter:
This will throw a NullPointerException when given head is null. So you might want to handle that.
So true :)
here is problem solution in java python c++ c and javascript programming. https://programs.programmingoneonone.com/2021/05/hackerrank-print-in-reverse-solution.html
So true. :D
void ReversePrint(Node *head) { // This is a "method-only" submission. // You only need to complete this method. if(head){ ReversePrint(head->next); printf("%d\n",head->data); } }
could you please explain your solution? Thanks!!
My only conern with this is that a LinkedList could be quite long, and the recursion depth limit is usually only around 5000, which really isn't that deep.
I did not understand the logic. Can you please explain? Thanks!
I took sophist_pt's code and altered it a bit to hopefully make it more intuitive.
Here's a code trace for an example. We have a linked list of three elements [1] -> [2] -> [3] Let's begin by calling the head.
So we just built this recursive stack. [RevPr1(RevPr2(RevPr3(RevPr4)))] Now we have to execute the function that is innermost. Why? Because that's where we were most recently!
This function was written from sophist_pt's brilliant code.
Got it. Thanks!
Youre amazing thank you
My pleasure! Recursion hurts my brain too... But eventually with enough practice one is able to understand when and how recursion is useful. (Hopefully without spending a half-hour to trace the process out like I did.)
void ReversePrint(Node *head) { // This is a "method-only" submission. // You only need to complete this method. if(head){ ReversePrint(head->next); printf("%d\n",head->data); } }
Really helpfull!!
Many thanks.. this helped tremendously
:D
Very educational. Thank you!
Hi ,Could you give more details about 2nd paragraph .How it's >[RevPr1(RevPr2(RevPr3()))]?
I've been seeing recursion a lot and only vaguely understand it, but with your explanation, it's all clear now. Thank you!
Thank you!!!
Great explanation
Seriously amazing, should be a teacher or a prof.
This comment will probably get burried, but basically...if i understood this correctly, the last one who calls and enters the if (head != null) get's to do the print statement first.
Then it unravells until the first one who called the if statements get's their turn to print it out.
that made it a little more clearer . thanks :)
Your explanation was very helpful..
That was a beauty. I believe you cleared the concepts of all recursive functions for me.
massssss...
UR FUCKIN AWEOSME MAN
beautiful explanation. One of the clearest I've seen on recursion honestly lol
awesome explained recursion . it help for beginner ! keep it.
thank you so much!
Thank you so much
thanks a lot bro..
Thanks man for the explanation.
it really helps!
Thoroughly explained!
I read many explanation but i didnt get it. After reading your explanation i got it. Thanks
Wow.. Great explanation
May god bless you my friend, You are amazing!
Excellent explanation! sophist_pt's answer (and the other recursion answers) confused me. From reading yours I understood it and realized I need some more work on recursion! Thanks!
Thank u so much bro now i can understand the code
this explanation is amazing. thanks a lot
does recursion allow as to move one step backward i dont no why you say that we just built this recursive stack. [RevPr1(RevPr2(RevPr3(RevPr4)))] in which line does it mean that and if it is a stsck so we moves backward why does it read the only last code (print (head.data)) i am sorry if i didnot explain my problem in easy way so you can understand me as i am a beginner thanks for your explanation
bro you are lit.!
Thanks a lot well explained .
Thank you very much for explaining to me. Could you give some resources so that i can understand recursion well
Start writing the normal, fibnocci, prime numbers, even/odd and so on programs using recursion, it will help to improve your understanding.
Thank you, this helped me understand recursive more :)
thanks
fantastic!
void ReversePrint(Node *head) { // This is a "method-only" submission. // You only need to complete this method. if(head){ ReversePrint(head->next); printf("%d\n",head->data); } }
best logic!!!
I don't know why this solution causes runtime exception...? Did this happen to someone else ?
Have you figured it out? Can you post your code? Both versions of the solution above work.
Thanks a lot
Hi,
I got this runtime exception as well. For me, it was for the Test Case #1 where they have an input of just 0 for one of there queries. Normally, it is a number for the # of nodes in the linked list followed by a set of numbers that need to be reversely printed.
You can test it out by using custom input of the Test Case #1 input and removing the 0 from the input data and changing the first 5 to 4 queries after.
can u please explain your code, the recursion part in particular
I think it is better just write if(head != null) instead of if-else.
I wonder can it break the stack with sufficient linked-list length?
It can and will
Yeah. Recursive solutions generally don't work well when n is very big because of the demands on the stack. Classic example is computing the Fibonacci numbers. Compare the recurisve solution against the iterative one.
Yes, I agree and this can be an important consideration for large data sets or relatively large data sets on platforms with restricted stack sizes. If Hackerrank doesn't already, I think they could include variations on problems like this that enforce iterative solutions.
This immediately came to mind for me. It might look really nice, and really neat, but you would never do this in reality. You run the risk of overflowing the stack.
Beautiful!
Hi , How this code will display reverse data?
This may be helpful in understanding recursion better if you didn't get StefanK's explanation. https://www.youtube.com/watch?v=neuDuf_i8Sg
Thanks a lot!!!
You vs. the guy she tells you not to worry about
C++ solution
how it works??
-
It's through recursion, ex : 1->4->8->9 In this first the head will move till head is NULL and then returns control to the previous call then printing of the last ele is done then the control is returned to the previous call then printing of the last second ele and so on.
really...its a wonderful thought
Who do I know that it's traversing in the reverse direction? It's not a double linked list so it's hard to go back when you can only move forward...
i have done without recurrsion:
void ReversePrint(Node head) {
}
same here in C#:
**
**
if (head != null) { ReversePrint(head.Next); Console.WriteLine(head.Data); }
Using ArrayList :
static void reversePrint(SinglyLinkedListNode head) { SinglyLinkedListNode temp; ArrayList cars = new ArrayList(); temp = head; while(temp!=null) { cars.add(temp.data); temp = temp.next; } for(int i = cars.size()-1; i>=0; i--) { System.out.println(cars.get(i)); } }
this code is similar to yours but it gives a null pointer exception.can you explain why?
Because you are first putting it as head.next which means if it IS null, it will already be at head.next and the return will basically return to the pre-recursion of the last function just to get print a null value
What his code does is, if head.next is null, it will return so that head.data will be printed, otherwise, head=head.next will happen and that will be put into the same function
Even denser in Python:
Can you plz explain how recursion works here
By calling the function recursively before the print statement, you first get to the end of the linked list and print the final value, print the last but 1 value, etc until you print the first value.
here's my take to it
C#
I'm not from Java, but if there is no special kind of execution queue, code above should print in the direct order, not in reversed. So why?
My Simplest C Solution:
This is brilliant! Please take my very first comment on Hackkerank.
python3
Is the reversePrint method an inbuilt method???
no I declared that
wow, that's beautiful.
I could never think of such a short and neat approach. here is my bruteForce method:-
static void reversePrint(SinglyLinkedListNode head) { ArrayList<Integer> pl=new ArrayList(); SinglyLinkedListNode temp=head; while(temp!=null){ pl.add(temp.data); temp=temp.next; } Collections.reverse(pl); for(int i:pl){ System.out.println(i); }
wow!! What a logic:
Iterative code in Python
A Python3 version
Python3:
def reversePrint(head)
Using recursion in C++
sweet :)