Saturday, 18 April 2015

Hackerrank Print the elements of a linked list solution

Problem Statement


This challenge is part of a tutorial track by MyCodeSchool and is accompanied by a video lesson.

If you’re new to working with linked lists, this is a great exercise to get familiar with them. You’re given the pointer to the head node of a linked list and you need to print all its elements in order, one element per line. The head pointer may be null, i.e., it may be an empty list. In that case, don’t print anything!

Source code:

 /*  
  Print elements of a linked list on console   
  head pointer input could be NULL as well for empty list  
  Node is defined as   
  struct Node  
  {  
    int data;  
    struct Node *next;  
  }  
 */  
 void Print(Node *head)  
 {  
  // This is a "method-only" submission.   
  // You only need to complete this method.   
   while(head!=NULL){  
     cout<<head->data<<endl;  
     head = head->next;  
   }  
 }  

** The above solution is my own code and it may not be the optimal solution or optimal way to approach the problem but it passes all the testcases in Hackerrank. So if you have any optimal approaches feel free to paste the code as the comment below..... :) :) :)

2 comments:

  1. I had the same problems and spent a lot of money to solve it. Thank you! I wish your blog be successful, that's w hy visit custom writing paper and see what our professionals propose you to do!

    ReplyDelete
  2. This is actually quite interesting. The code you came up with is totally useful and it really shows your creativity level :) Thank you for posting!

    ReplyDelete