Saturday, 18 April 2015

Hackerrank Reverse a linked list solution

Problem Statement

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

You’re given the pointer to the head node of a linked list. Change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty.

source code:

 /*  
  Reverse a linked list and return pointer to the head  
  The input list will have at least one element   
  Node is defined as   
  struct Node  
  {  
    int data;  
    struct Node *next;  
  }  
 */  
 Node* Reverse(Node *head)  
 {  
  // Complete this method  
   Node *prev = NULL;  
   Node *cur = head;  
   Node *next ;  
   while(cur!=NULL){  
     next = cur->next;  
     cur->next = prev;  
     prev = cur;  
     cur = next;  
   }  
   head = prev;  
   return head;  
 }  
** 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..... :) :) :)

1 comment:

  1. not working, still there is error due to unformatted output

    ReplyDelete