Part 7 of 22 in Linked List - set 01  

Insert a node in a linked list at head by admin

Problem statement

Given pointer to the head of a singly linked list, write a function to add a node at the beginning of the list

Input

Your method will contain two arguments - pointer to the head of the linked list and an integer to be inserted into the list.

Output

You must complete the given method and return a pointer to the head of the linked list. See coding panel for method signature.

1) Are you writing main function and definition of Node also?  
    You only need to write the function asked for in input description. 

First we have to allocate memoty to a pointer of type Node using the malloc function and let us name it as new_head. Then we assign the given data to the 'data' varible of the new_head.

Now we assign the 'next' pointer of the new_head to the given head. So, basically what we have done is, we have created a new node and attached the given list to the front of it, thus making the new node as the head of the given list.

editorial written by i_coder

/*
  Insert Node at the begining of a linked list
  Initially head pointer argument could be NULL for empty list
  Node is defined as 
  struct Node
  {
     int data;
     struct Node *next;
  }
return back the pointer to the head of the linked list in the below method.
*/
Node* Insert(Node *head,int data)
{
    //Allocare memory to a pointer of type Node using the malloc function
    Node *new_head = (Node*) malloc (sizeof (Node));
    //set the data of the new pointer to given data
    new_head->data = data;
    //Assign the 'next' pointer of the current node to the given
    //head of the linked list
    new_head->next = head;
    //Return the pointer of the new node
    return new_head;
}

featured solution by i_coder



To try out your code



Sign in

Sign up