• + 34 comments

    You could do it recursively which is a lot neater. The code below is in Java.

    void ReversePrint(Node head) {

    if(head == null)
        ;
    else{
        ReversePrint(head.next);
        System.out.println(head.data);
    }
    

    }

    • + 5 comments

      Recursion never felt so good :D

      • + 3 comments

        That conditional is a bit ugly, why not

        if(head == null) return;
        ReversePrint(head.next);
        System.out.println(head.data);
        
        // OR
        
        if (head != null) {
           ReversePrint(head.next);
           System.out.println(head.data); 
        }
        
        • + 1 comment

          nice

          • + 1 comment
            [deleted]
            • + 0 comments

              here is problem solution in python java c++ and c programming. https://solution.programmingoneonone.com/2020/07/hackerrank-print-in-reverse-solution.html

        • + 1 comment

          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.

          • + 0 comments

            here is problem solution in python java c++ and c programming. https://solution.programmingoneonone.com/2020/07/hackerrank-print-in-reverse-solution.html

        • + 3 comments

          Even shorter:

          static void reversePrint(SinglyLinkedListNode head) {
                  if(head.next!=null) reversePrint(head.next);
                  System.out.println(head.data);
          
              }
          
          • + 0 comments

            This will throw a NullPointerException when given head is null. So you might want to handle that.

      • + 1 comment

        So true :)

        • + 0 comments

          here is problem solution in java python c++ c and javascript programming. https://programs.programmingoneonone.com/2021/05/hackerrank-print-in-reverse-solution.html

      • + 0 comments

        So true. :D

      • + 1 comment

        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); } }

        • + 1 comment

          could you please explain your solution? Thanks!!

      • + 0 comments

        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.

    • + 3 comments

      I did not understand the logic. Can you please explain? Thanks!

      • + 36 comments

        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.

        • + 0 comments

          Got it. Thanks!

        • + 2 comments

          Youre amazing thank you

          • + 0 comments

            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.)

          • + 1 comment

            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); } }

            • + 0 comments

              Really helpfull!!

        • + 0 comments

          Many thanks.. this helped tremendously

          :D

        • + 0 comments

          Very educational. Thank you!

        • + 0 comments

          Hi ,Could you give more details about 2nd paragraph .How it's >[RevPr1(RevPr2(RevPr3()))]?

        • + 0 comments

          I've been seeing recursion a lot and only vaguely understand it, but with your explanation, it's all clear now. Thank you!

        • + 1 comment

          Thank you!!!

        • + 1 comment

          Great explanation

        • + 1 comment

          Seriously amazing, should be a teacher or a prof.

        • + 1 comment

          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.

          • + 1 comment

            that made it a little more clearer . thanks :)

        • + 0 comments

          Your explanation was very helpful..

        • + 1 comment

          That was a beauty. I believe you cleared the concepts of all recursive functions for me.

        • + 0 comments

          massssss...

        • + 0 comments

          UR FUCKIN AWEOSME MAN

        • + 0 comments

          beautiful explanation. One of the clearest I've seen on recursion honestly lol

        • + 0 comments

          awesome explained recursion . it help for beginner ! keep it.

        • + 0 comments

          thank you so much!

        • + 0 comments

          Thank you so much

        • + 0 comments

          thanks a lot bro..

        • + 0 comments

          Thanks man for the explanation.

        • + 0 comments

          it really helps!

        • + 0 comments

          Thoroughly explained!

        • + 0 comments

          I read many explanation but i didnt get it. After reading your explanation i got it. Thanks

        • + 0 comments

          Wow.. Great explanation

        • + 0 comments

          May god bless you my friend, You are amazing!

        • + 0 comments

          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!

        • + 0 comments

          Thank u so much bro now i can understand the code

        • + 0 comments

          this explanation is amazing. thanks a lot

        • + 0 comments

          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

        • + 0 comments

          bro you are lit.!

        • + 0 comments

          Thanks a lot well explained .

        • + 1 comment

          Thank you very much for explaining to me. Could you give some resources so that i can understand recursion well

          • + 0 comments

            Start writing the normal, fibnocci, prime numbers, even/odd and so on programs using recursion, it will help to improve your understanding.

        • + 0 comments

          Thank you, this helped me understand recursive more :)

        • + 0 comments

          thanks

      • + 0 comments

        fantastic!

      • + 1 comment

        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); } }

        • [deleted]
          + 0 comments

          best logic!!!

    • + 2 comments

      I don't know why this solution causes runtime exception...? Did this happen to someone else ?

      • + 1 comment

        Have you figured it out? Can you post your code? Both versions of the solution above work.

        • [deleted]
          + 1 comment
          [deleted]
          • + 0 comments

            Thanks a lot

      • + 0 comments

        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.

    • + 0 comments

      can u please explain your code, the recursion part in particular

    • + 0 comments

      I think it is better just write if(head != null) instead of if-else.

    • + 4 comments

      I wonder can it break the stack with sufficient linked-list length?

      • + 0 comments

        It can and will

      • + 0 comments

        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.

      • + 0 comments

        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.

      • + 0 comments

        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.

    • + 0 comments

      Beautiful!

    • + 1 comment
      if(head == null)
          {
          return;
      }
      ReversePrint(head.next);
      System.out.println(head.data);
      
      This code is more optimized and effiecient.
      
      • + 1 comment

        Hi , How this code will display reverse data?

        • + 0 comments

          This may be helpful in understanding recursion better if you didn't get StefanK's explanation. https://www.youtube.com/watch?v=neuDuf_i8Sg

    • + 0 comments

      Thanks a lot!!!

    • + 0 comments

      You vs. the guy she tells you not to worry about

    • + 2 comments
      void ReversePrint(Node *head){
          if(head==NULL) return;
          else{
              ReversePrint(head->next);
              cout<<head->data<<endl;
          }
      }
      

      C++ solution

      • + 1 comment

        how it works??

          -
        • + 0 comments

          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.

      • + 0 comments

        really...its a wonderful thought

    • + 0 comments

      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...

    • + 2 comments

      i have done without recurrsion:

      void ReversePrint(Node head) {

      Node node=head;
      Node node1=head;
      int c=0;
      while(node!=null)
      {
          c++;
          node=node.next;
      }
      //System.out.println(c);
      int arr[]=new int[c];
      int i=0;
      
      while(node1!=null)
      {
          arr[i]=node1.data;
          i++;
          node1=node1.next;
      
      
      }
      int j;
       if(c>0)
       {
      for(j=(c-1);j>=0;j--)
      {
          System.out.println(arr[j]);
      }
      
      }
      

      }

      • + 1 comment

        same here in C#:

        **

        public static void ReversePrint(Node head) {
           if (head != null) {
             var tempNode = head;
             var counter = 1;
             while (tempNode.Next != null) {
               ++counter;
               tempNode = tempNode.Next;
             }
             int[] arr = new int[counter];
        
             counter = 1;
             tempNode = head;
             while (tempNode.Next != null) {
               arr[counter - 1] = tempNode.Data;
               ++counter;
               tempNode = tempNode.Next;
             }
             arr[counter-1] = tempNode.Data;
             for (int i = arr.Length - 1; i >= 0; --i) {
               Console.WriteLine(arr[i]);
             }
           }
        
         }
        

        **

        • + 0 comments

          if (head != null) { ReversePrint(head.Next); Console.WriteLine(head.Data); }

      • + 0 comments

        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)); } }

    • + 1 comment

      this code is similar to yours but it gives a null pointer exception.can you explain why?

      if(head==null){
          return;
      }
      else{
          head=head.next;
          ReversePrint(head);
          System.out.println(head.data);
      }
      
      • + 0 comments

        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

    • + 1 comment

      Even denser in Python:

      def ReversePrint(head):
          if head:
              ReversePrint(head.next)
              print(head.data)
      
      • + 1 comment

        Can you plz explain how recursion works here

        • + 0 comments

          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.

    • + 0 comments

      here's my take to it

      void ReversePrint(Node *head)
      {if(!head)
          return;
          
       ReversePrint(head->next);
       printf("%d\n",head->data);
          
        }
      
    • + 0 comments

      C#

      public static void ReversePrint(Node head)
          {
              if (head != null){
                  ReversePrint(head.Next);
                 Console.WriteLine(head.Data);
              }
          }
      
    • + 0 comments

      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?

    • + 0 comments

      My Simplest C Solution:

      void reversePrint(SinglyLinkedListNode* head) {
          if(head->next) reversePrint(head->next);
          printf("%d\n",head->data);
      }
      
    • + 0 comments

      This is brilliant! Please take my very first comment on Hackkerank.

    • + 0 comments

      python3

      class Node:
          def __init__(self,data):
              self.data=data
              self.next=None
      class SinglyLinkedList:
          def __init__(self):
              self.head=None
          def insert_node(self,data):
              node=Node(data)
              node.next=self.head
              self.head=node
      def reversePrint(head):
          current=head
          while current:
              print(current.data)
              current=current.next
      
    • + 1 comment

      Is the reversePrint method an inbuilt method???

      • + 0 comments

        no I declared that

    • + 0 comments

      if(head==null) System.out.println(""); else{ List list=new ArrayList(); while(head!=null){ list.add(head.data); head=head.next; } Collections.reverse(list); for(Integer d:list){ System.out.println(d); } }

    • + 0 comments

      wow, that's beautiful.

    • + 0 comments

      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); }

    • + 0 comments

      wow!! What a logic:

    • + 0 comments

      Iterative code in Python

      def reversePrint(head):
          x = head
          l = []
          if head is not None:
              while(x is not None):
                  l.append(x.data)
                  x = x.next
              print('\n'.join(map(str, l[::-1])))
      
    • + 0 comments

      A Python3 version

      def reversePrint(head):
          if head:
              reversePrint(head.next)
              print(str(head.data))
          else:
              return
      
    • + 0 comments

      Python3:

      def reversePrint(head)

      if head.next == None:
          print(head.data)
          return
      reversePrint(head.next)
      print(head.data)
      
    • + 0 comments

      Using recursion in C++

      void reversePrint(SinglyLinkedListNode* llist) {
      
          SinglyLinkedListNode *p = llist;
          if(p!=NULL){
              reversePrint(p->next);
              cout<<p->data<<'\n';
          }
      
      
      }
      
    • + 0 comments

      sweet :)