Insert Node at the beginning of linked list

Write a function to insert node or element at the beginning of linked list. C Program to insert node or element at the beginning of linked list.
Here we want to insert node at first position. So there are two condition if list is empty and if list is not empty.

if list is empty that means head node pointing to NULL and we have a new node with data n. So we can connect new node to head node by pointing head node to the new node.

If list is not empty then head node is not pointing to NULL. First connect new node to the head node by pointing newNode->next to head. and then point head node to newNode.






C Program:

#include<stdio.h>
#include<stdlib.h>
 
struct Node
{
 int data;
 struct Node *next;
};
 
/* Function to create new node that take one integer and 
return the address of node */
struct Node *CreateNode(int n)
{
 /* Create a new node in which data is n and pointer next
 is pointing to NULL */
struct Node *newNode=(struct Node*)malloc(sizeof(struct Node));
 newNode->data = n;
 newNode->next = NULL;
 return newNode;
}
 
struct Node *InsertAtBeginning(struct Node *head, int n)
{
 /* Get new node by calling function CreateNode() */
 /* We can create new node in this function also as
 
 struct Node *newNode=(struct Node*)malloc(sizeof(struct Node);
 newNode->data = n;
 newNode->next = NULL;
 */
 struct Node *newNode = CreateNode(n);
 
 /* If head is pointing to NULL then add newNode at the first
 position by pointing head to newNode */
 if(head==NULL)
 {
  head = newNode;
 }
 else
 {
  newNode->next = head;
  head = newNode;
 }
 
 return head;
}
 
void PrintList(struct Node *head)
{
 struct Node *curr = head;
 
 if(curr==NULL)
 {
  printf("List is empty\n");
 }
 else
 {
 while(curr!=NULL)
 {
  printf("%d ",curr->data);
  curr = curr->next; 
 }
 }
     printf("\n");
}
 
int main()
{
 struct Node *head = NULL;
 
 /* Print list when head is pointing to NULL
 or there is no node in list */
 
 PrintList(head);
 
 head = InsertAtBeginning(head,12);
 head = InsertAtBeginning(head,78);
 head = InsertAtBeginning(head,65);
 head = InsertAtBeginning(head,28);
 
 PrintList(head);
 
 return 0;
}



Popular posts from this blog