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 first allocate memory space for new node. Then we will take a pointer variable temp and initialize it with HEAD that is, temp will point to the first node. Then we will store the value to be inserted in new node's data part. In while loop, we will traverse through the linked list to reach the node after which we want to insert new node. Once reached, we will point the next pointer in such a way that the new node is inserted after desired node.
Algorithm-
Step 1: If AVAIL = NULL
Write overflow
Go to Step 9
[End of If]
Step 2: Set NEW_NODE = AVAIL
Step 3: Set AVAIL = AVAIL ➡ NEXT
Step 4: Set NEW_NODE ➡ DATA = VAL
Step 5: Set PTR = HEAD
Step 6: Repeat Step 7 while PTR ➡ DATA != VAL
Step 7: Set PTR = PTR ➡ NEXT
[End of Loop]
Step 8: Set NEW_NODE ➡ NEXT = PTR ➡ NEXT
Step 9: Set PTR ➡ NEXT = NEW_NODE
Step 10: EXIT
C program to insert a node after a given node in singly linked list-
#include <stdio.h>
#include <malloc.h>
struct node
{
int data;
struct node* next;
};
void insertatend(struct node** head)
{
int n;
printf("Enter value to insert at end: ");
scanf("%d",&n);
struct node* val=(struct node*)malloc(sizeof(struct node));
val->data=n;
val->next=NULL;
if(*head==NULL)
{
*head=val;
return;
}
struct node* t=*head;
while(t->next!=NULL)
{
t=t->next;
}
t->next=val;
}
void insertafernode(struct node** head)
{
int n;
printf("Enter value of node after which you want to insert : ");
scanf("%d",&n);
struct node* nw=(struct node*)malloc(sizeof(struct node));
struct node* temp=*head;
while(temp->data!=n)
{
temp=temp->next;
}
nw->data=12;
nw->next=temp->next;
temp->next=nw;
}
void display(struct node* head)
{
struct node* t=head;
while(t!=NULL)
{
printf("%d => ",t->data);
t=t->next;
}
printf("NULL \n");
}
int main()
{
struct node* head=NULL;
insertatend(&head);
insertatend(&head);
insertatend(&head);
insertafernode(&head);
display(head);
return 0;
}Enter value to insert at end: 9
Enter value to insert at end: 10
Enter value to insert at end: 11
Enter value of node after which you want to insert : 10
9 => 10 => 12 => 11 => NULL

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