C Programming language

adplus-dvertising
C - Singly linked list, Insertion
Previous Home Next

Based upon various type of insertions, the insertion in a singly linked list can be done in three ways :

  1. Insertion at the end of the list.
  2. Insertion at the beginning of the list.
  3. Insertion at the specified position in the list.

Now, following below is a program that incorporates all the tree types of insertion methods and shows how to do all these types of insertions.

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<process.h>
struct node
    {
int num;
struct node *next;
};                            /* declaring a global node of type struct */
typedef struct node NODE;    /* providing a type definition to the above created structure */
NODE *head=NULL;             /* declaring some of the global variable that would be used thought out the program */
NODE *temp, *first;
int info;
void display();
void insert_at_end();
void insert_at_begin();
void insert_at_specifiedpos();
void main()                                 /* starting the main method() */
{
int i;
clrscr();
printf("\nprogram for insertion in a singly linked list :\n");
do
{
printf("\nEnter your choice :\n");      /* creating menu for various insertion operations on the list */
printf("\n1.Insert element at the end of the linklist :");
printf("\n2.Insert element at the begin of the linklist :");
printf("\n3.Insert at any specified position in the linked list :");
printf("\n4.Exit\n");
fflush(stdin);
scanf("\n%d",&i);
switch(i)
{
case 1:
insert_at_end();
display();
break;
case 2:
insert_at_begin();
display();
break;
case 3:
insert_at_specifiedpos();
display();
break;
case 4:
exit(0);
}
}
while(i<=4);
getch();
}
void insert_at_end()
{
printf("\nEnter your element in the linked list :");
scanf("%d",&info);
temp=(NODE *)malloc(sizeof(NODE));         /* allocating memory for the node to be inserted */
temp->num=info;
temp->next=NULL;
if(head==NULL)                            /* checking whether list is empty */
{
head=temp;
}
else
{
first=head;
while(first->next!=NULL)
{
first=first->next;
}
first->next=temp;
}
}
void display()
{
first=head;
printf("\nStatus of the linked list is as follows :\n");
while(first->next!=NULL)                    /* traversing the linked list */
{
printf("\n%d",first->num);
first=first->next;
}
}
void insert_at_begin()
{
printf("\nEnter the value which do you want to insert at begining\n");
scanf("\n%d"&info);
first=head;
temp=(NODE *)malloc(sizeof(NODE));
temp->num=info;
temp->next=first;
head=temp;
}
void insert_at_specifiedpos()
{
int info1,info2;
printf("\nEnter the value after which you want to insert new node\n");
scanf("%d",&info1);
printf("\nEnter the value of new node\n");
scanf("\n%d",&info2);
temp=(NODE *)malloc(sizeof(NODE));
temp->num=info2;
temp->next=NULL;
first=head;
while(first->num!=info1)
{
first=first->next;
}
temp->next=first->next;
first->next=temp;
}
}
Previous Home Next