Here we are going to write a c program to insert node at the beginning of a singly linked list. Before we proceed, if you don't have basic knowledge of linked list or want to learn everything about singly linked list at one go then you must visit singly linked list post which is a part of our dsa series and also types of linked list series.
Ok Now How will we do this means insertion of node at the beginning of singly linked list.
We will first allocate memory space for new node. Set its DATA part with the value and the NEXT part is initialized with the address of the first node stored in HEAD. Since we are adding the new node at the beginning i.e., it will be our first node. So now we will point HEAD towards this new node that is HEAD will store the address of this new node.
Algorithm-
Step 1: IF AVAIL = NULL
Write OVERFLOW
Go to Step 7
[END OF IF]
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL ➡ NEXT
Step 4: SET DATA = VAL
Step 5: SET NEW_NODE ➡ NEXT = START
Step 6: SET START = NEW_NODE
Step 7: EXIT
C Program to Insert node at the Beginning of a Singly Linked List-
#include <stdio.h>
#include <malloc.h>
struct node
{
int data;
struct node* next;
};
void insertatbeg(struct node** head)
{
int n;
printf("Enter value to insert at beginning: ");
scanf("%d",&n);
struct node* val=(struct node*)malloc(sizeof(struct node));
val->data=n;
val->next=*head;
*head=val;
}
void display(struct node* head)
{
struct node* t=head;
while(t!=NULL)
{
printf("%d => ",t->data);
t=t->next;
}
printf("NULL \n");
}
struct node* head=NULL;
void main()
{
insertatbeg(&head);
display(head);
}Output-
Enter value to insert at beginning: 2
2 => NULLVisual Representation-

Post a Comment
If you have any doubts, please let me know