In this HackerRank Day 15 Linked List 30 days of code problem Complete the insert function in your editor so that it creates a new Node (pass data as the Node constructor argument) and inserts it at the tail of the linked list referenced by the head parameter. Once the new node is added, return the reference to the head node.  


Day 15 Linked List 30 days of code hackerrank solution


Problem solution in Python 2 programming.

    def insert(self,head,data): 
        #Complete this method
        node = Node(data)
        if head == None:
            head = node
        else:
            current = head
            while current.next:
                current = current.next
            current.next = node
        return head


Problem solution in Python 3 programming.      

    def insert(self,head,data): 
        temp = Node(data)
        if head is None:
            head = temp
            return head
        current = head
        while current.next is not None:
            current = current.next
        current.next = temp
        return head       

Problem solution in java programming.

    public static  Node insert(Node head,int data){
        // if list has no elements, return a new node
        if(head == null){
            return new Node(data);
        }
        
        // else iterate through list, add node to tail, and return head
        Node tmp = head;
        while(tmp.next != null){
            tmp = tmp.next;
        }
        tmp.next = new Node(data);
            
        return head;
	}


Problem solution in c++ programming.

      Node* insert(Node *head,int data)
      {
          //Complete this method
          if(head == nullptr){
              return new Node(data);
          }
          
          Node *temp = head;
          while(temp->next != nullptr){
              temp = temp->next;
          }
          
          temp->next = new Node(data);          
          return head;
      }


Problem solution in c programming.

Node* insert(Node *head,int data)
{
    //Complete this function
    struct Node *ll, *it;
    ll=(struct Node *)malloc(sizeof(struct Node));
    ll->data=data;
    ll->next=NULL;
    
    if(head==NULL)
        {
        head=ll;
    }
    else
        {
        it=head;
        while(it->next)
            it=it->next;
        it->next=ll;
    }
    return head;
}


Problem solution in Javascript programming.

    this.insert=function(head,data){
        //complete this method
        var newNode = new Node(data);

        if (head === null || typeof head === 'undefined') {
            head = newNode;  
        } else if (head.next === null) {
            head.next = newNode;
        } else {
            var next = head.next;
            while(next.next) {
                next = next.next
            }
            next.next = newNode;
        }
        
        return head;
    };