Experiment 1: Write A C Programme To Perform The Following Operation On A Single Linked List (I) Creation (Ii) Insertion (Iii) Traverse Program
Experiment 1: Write A C Programme To Perform The Following Operation On A Single Linked List (I) Creation (Ii) Insertion (Iii) Traverse Program
Program:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int info;
struct node *link;
};
struct node *head,*ptr,*temp;
void insert_beg();
void insert_end();
void insert_any();
void display();
void main()
{
int item,ch,c=1;
clrscr();
head->info=NULL;
head->link=NULL;
while(c==1)
{
printf("\nDISPLAY MENUES\n");
printf("\n1.INSERT_BEG\n");
printf("\n2.INSERT_END\n");
printf("\n3.INSERT_ANY\n");
printf("\n4.DISPLAY\n");
printf("\nEnter Your Choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: insert_beg();
break;
case 2: insert_end();
break;
case 3: insert_any();
break;
case 4: display();
break;
}
printf("\nDo You Want To Continue(1/0)");
scanf("%d",&c);
}
getch();
}
/************INSERT AT BEGING***************/
void insert_beg()
{
int item;
printf("\nEnter The Item\n");
scanf("%d",&item);
temp=(struct node*)malloc(sizeof(struct node));
temp->info=item;
temp->link=head;
head=temp;
}
/************INSERT AT END***************/
void insert_end()
{
int item;
printf("\nEnter The Item\n");
scanf("%d",&item);
temp=(struct node*)malloc(sizeof(struct node));
ptr=head;
while(ptr->link!=NULL)
{
ptr=ptr->link;
}
temp->info=item;
temp->link=ptr->link;//sending last node null into new node link i.e null
ptr->link=temp;// sending new node address into previous last node link
}
/************INSERT AT ANY POSITION***************/
void insert_any()
{
int item,key;
printf("\nEnter The Item\n");
scanf("%d",&item);
printf("\nEnter The Key Element:\n");
scanf("%d",&key);
temp=(struct node*)malloc(sizeof(struct node));
ptr=head;
while(ptr->link!=NULL&&ptr->info!=key)
{
ptr=ptr->link;
}
if(ptr->info==key)
{
temp->info=item;
temp->link=ptr->link;//sending address of current node into new node
ptr->link=temp;//sending the address of new node into current node
}
else
{
printf("Key Element Is Not Found:%d",key);
}
}
/************DISPLAY THE ELEMENTS***************/
void display()
{
int item;
ptr=head;
while(ptr!=NULL)
{
printf("%d",ptr->info);
ptr=ptr->link;
}
}
PROGRAM : 2 : Write a C program that uses functions to perform the following operations on
doubly linked list.:
i) Creation ii) Insertion iii) Traversal in both ways