Saturday, 18 April 2015

Hackerrank Insert a node at a specific position in 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, an integer to add to the list and the position at which the integer must be inserted. Create a new node with the given integer, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is empty.

source code:

 /*  
  Insert Node at a given position in a linked list   
  The linked list will not be empty and position will always be valid  
  First element in the linked list is at position 0  
  Node is defined as   
  struct Node  
  {  
    int data;  
    struct Node *next;  
  }  
 */  
 Node* InsertNth(Node *head, int data, int position)  
 {  
  // Complete this method only  
  // Do not write main function.  
   Node *cur = new Node,*temp = new Node;  
   temp->data = data;  
   temp->next = NULL;  
   if(head == NULL){  
     head = temp;  
   }else{  
     int i=0;  
     cur = head;  
     while(cur!=NULL){  
       if(position == 0){  
           temp->next = cur;  
           head= temp;  
       }  
       else if(i==position-1){  
         temp->next = cur->next;  
         cur ->next = temp;  
       }else{  
       }i++;  
       cur= cur->next;  
     }  
   }  
   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..... :) :) :)

4 comments:

  1. Node InsertNth(Node head, int data, int position) {
    // This is a "method-only" submission.
    // You only need to complete this method.
    Node temp=new Node();
    temp.data=data;

    if(head==null){
    temp.next=null;
    head=temp;
    }else{
    int i=0;
    while(head.next!=null){
    if(position==0){
    temp.next=head;
    head=temp;
    }else if(i==position-1){
    temp.next=head.next;
    head.next=temp;
    }
    head=head.next;
    i++;
    }
    }
    return head;
    }

    This is my code not sure why its not giving desired output

    ReplyDelete
  2. This code didn't passed all cases in HackerRank

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete