Saturday, 18 April 2015

Hackerrank Insert a node at the tail of 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 and an integer to add to the list. Create a new node with the given integer, insert this node at the tail of the linked list and return the head node. The head pointer given may be null meaning that the initial list is empty.

source code:

 /*  
  Insert Node at the end of a linked list   
  head pointer input could be NULL as well for empty list  
  Node is defined as   
  struct Node  
  {  
    int data;  
    struct Node *next;  
  }  
 */  
 Node* Insert(Node *head,int data)  
 {  
  // Complete this method  
   Node *cur= new Node;  
   cur->data = data;  
   cur->next = NULL;  
   if(head==NULL){  
     head = cur;  
   }else{  
     Node *curr = new Node;  
     curr = head;  
     while(curr->next !=NULL){  
       curr = curr->next;  
     }  
     curr->next = cur;  
   }  
     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..... :) :) :)

2 comments:

  1. Node *curr = new node ;
    //optimal way :
    curr = new node; no need to do it twice

    ReplyDelete

  2. Node Insert(Node head, int data) {
    Node n = new Node();
    n.data = data;
    n.next = null;

    if (head == null) {
    return n;
    } else {
    Node curr = head;
    while (curr.next != null) {
    curr = curr.next;
    }
    curr.next = n;
    return head;
    }
    }

    ReplyDelete