Ex. No: 1b IMPLEMENTATION OF DOUBLY LINKED LIST
AIM:
To write a c program to implement the doubly linked list.
ALGORITHM:
Step1: Start the program.
Step2: Declare the structure named as node with two fields (address)
and one data field pointing the previous and next node.
and one data field pointing the previous and next node.
Step3: CREATION
(a) Get the size of list that has to be created.
(b) Allocate the memory space for each node.
(c) Link all the nodes using pointer.
Step4: INSERTION
(a) Allocate memory space for new node.
(b) Get the position where the new node wants to be inserted.
(c) Change the links.
Step5: DELETION
(a)Get the position where the new node wants to be deleted.
(b) Change the links
Step6: DISPLAY
(a) Check whether the list is empty or not.
(b) If it is not empty print the data until the list address field is empty.
Step7: Stop the process.
PROGRAM:
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node*next;
struct node*prev;
};
struct node *start,*p,*new1;
int item,i,n,pos,num,null;
void display();
void create()
{
printf("\n Enter the size of the list:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
new1=(struct node*)malloc(sizeof(struct node));
printf("\n Enter the data:");
scanf("%d",&item);
new1->data=item;
new1->next=NULL;
new1->prev=NULL;
if(i==1)
{
start=new1;
p=new1;
}
else
{
p->next=new1;
new1->prev=p;
p=new1;
}
}
display();
}
void insert()
{
p=start;
printf("\n Enter the position:");
scanf("%d",&pos);
new1=(struct node*)malloc(sizeof(struct node));
printf("Enter the data:");
scanf("%d",&item);
new1->data=item;
new1->next=NULL;
new1->prev=NULL;
for(i=1;i<pos;i++)
p=p->next;
new1->next=p->next;
p->next=new1;
n=n+1;
display();
}
void delet()
{
printf("\n Enter the position:");
scanf("%d",&pos);
p=start;
for(i=1;i<pos;i++)
p=p->next;
p->next=p->next->next;
p->next->prev=p;
printf("\n node deleted");
n=n-1;
display();
}
void search()
{
p=start;
pos=0;
i=1;
printf("\n Enter the element to be found");
scanf("%d",&num);
while(p!=NULL)
{
if(p->data==num)
{
printf("Element is found at%dposition\n",i-1);
pos=i;
break;
}
else
p=p->next;
i++;
}
if(pos==0)
printf("\n Element is not found");
}
void display()
{
p=start;
for(i=1;i<=n;i++)
{
printf("%d",p->data);
p=p->next;
}
printf("NULL");
}
void main()
{
int c;
clrscr();
for(;;)
{
printf("\n*****MENU******");
printf("\n1.create");
printf("\n2.Insert");
printf("\n3.delete");
printf("\n4.search");
printf("\n5.display");
printf("\n6.exit");
printf("\n Enter the choice");
scanf("%d",&c);
switch(c)
{
case 1:
create();
break;
case 2:
insert();
break;
case 3:
delet();
break;
case 4:
search();
break;
case 5:
display();
break;
case 6:
exit();
break;
default:
printf("Enter the correct choice:");
getch();
}
}
}