In this HackerRank Day 15: Linked List problem solution 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.

HackerRank Day 15: Linked List problem solution

Problem solution in Python programming.

    def insert(self,head,data): 
    #Complete this method
        if not head:
            self.head = self.tail = Node(data)
        else:
            self.tail.next = self.tail = Node(data)
        return self.head
  


Problem solution in Java programming.

	public static Node insert(Node head,int data)
	{
        Node newNode = new Node(data);
        
        if (head == null) {
            return newNode;    
        }
        else {
            Node current = head;
            while (current.next != null)
            {
                current = current.next;
            }
            current.next = newNode;
            return head;
        }
	}




Problem solution in C++ programming.

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



Problem solution in C programming.

Node* insert(Node *head,int data)
{
    Node *temp = head;
    Node *new_node = malloc(sizeof(struct Node));
    new_node->data = data;
    new_node->next = NULL;
    if (head == NULL){        
        head = new_node;
    }    
    else{
        while(temp->next){
            temp = temp->next;
        }
        temp->next = new_node;
    }
    return head;
}



Problem solution in Java programming.

	this.insert=function(head,data){
          //complete this method
        
        if(head === null) return new Node(data);
        var temp = head;
        while(temp.next !== null) {
            temp = temp.next;
        }
        var node = new Node(data);
        temp.next = node;
        
        return head;
    };