Hackerrank Print in Reverse solution

Showing posts with label Hackerrank Print in Reverse solution. Show all posts
Showing posts with label Hackerrank Print in Reverse solution. Show all posts

Print a linked list in Reverse solution


Problem Statement

You're given the pointer to the head node of a linked list and you need to print all its elements in reverse order from tail to head, one element per line. The head pointer may be null meaning that the list is empty - in that case, don't print anything!

Soruce code:

 /*  
  Print elements of a linked list in reverse order as standard output  
  head pointer could be NULL as well for empty list  
  Node is defined as   
  struct Node  
  {  
    int data;  
    struct Node *next;  
  }  
 */  
 void ReversePrint(Node *head)  
 {  
  // This is a "method-only" submission.   
  // You only need to complete this method.   
   int a[100],i=0;  
   while(head!=NULL){  
     a[i] = head->data;  
     i++;  
     head = head->next;  
   }  
   for(int j = i-1;j>=0;j--){  
     cout<<a[j]<<endl;  
   }  
 }