Double Linked List lab program
#include <stdio.h>
#include <stdlib.h>
struct node
{
struct node *left;
int data;
struct node *right;
};
struct node *root=NULL;
void create()
{
struct node *second,*third,*fourth,*fifth;
clrscr();
root=malloc(sizeof(struct node));
second=malloc(sizeof(struct node));
third=malloc(sizeof(struct node));
fourth=malloc(sizeof(struct node));
fifth=malloc(sizeof(struct node));
root->data=10;
second->data=20;
third->data=30;
fourth->data=40;
fifth->data=50;
root->left=NULL;
root->right=second;
second->left=root;
second->right=third;
third->left=second;
third->right=fourth;
fourth->left=third;
fourth->right=fifth;
fifth->left=fourth;
fifth->right=NULL;
}
void addFirst(int val)
{
struct node *temp=malloc(sizeof(struct node));
temp->data=val;
if(root==NULL)
{
temp->left=NULL;
temp->right=NULL;
root=temp;
}
else
{
temp->left=NULL;
temp->right=root;
root->left=temp;
root=temp;
}
}
void addEnd(int val)
{
struct node *temp=malloc(sizeof(struct node));
temp->data=val;
if(root==NULL)
{
temp->left=NULL;
temp->right=NULL;
root=temp;
}
else
{
struct node *p;
p=root;
while(p->right!=NULL)
{
p=p->right;
}
p->right=temp;
temp->left=p;
temp->right=NULL;
}
}
void addposition(int val)
{
int pos,i=1;
struct node *temp,*p;
temp=malloc(sizeof(struct node));
temp->data=val;
temp->right=NULL;
printf("enter the position");
scanf("%d",&pos);
p=root;
while(i<pos)
{
p=p->right;
i++;
}
temp->right=p->right;
p->right=temp;
}
void deleteBEP(int val)
{
struct node *temp=root;
if(temp->data==val)
{
root=root->right;
root->left=NULL;
free(temp);
}
else
{
struct node *p=root;
while(p->right!=NULL)
{
if(p->right->data==val)
{
temp=p->right;
p->right=temp->right;
temp->right->left=p;
free(temp);
break;
}
else
{
p=p->right;
}
}
}
}
int search(int val)
{
struct node *temp;
temp=root;
while(temp!=NULL)
{
if(temp->data==val)
return 1;
temp=temp->right;
}
return -1;
}
void display()
{
struct node *temp;
temp=root;
while(temp!=NULL)
{
printf("%d--",temp->data);
temp=temp->right;
}
}
void main()
{
int op,val,x;
create();
while(1)
{
printf("\n linked list menu\n");
printf("1.insert at begin\n");
printf("2.insert at end\n");
printf("3.insert at pos\n");
printf("4.delete at beg,end,pos\n");
printf("5.search\n");
printf("6.display\n");
printf("7.exit\n");
printf("choose one option\n");
scanf("%d",&op);
switch(op)
{
case 1:printf("\n enter a value");
scanf("%d",&val);
addFirst(val);
break;
case 2:printf("\n enter a value");
scanf("%d",&val);
addEnd(val);
break;
case 3:printf("\n enter a value:");
scanf("%d",&val);
addposition(val);
break;
case 4:printf("\n enter a value:");
scanf("%d",&val);
deleteBEP(val);
break;
case 5:printf("\n enter a value:");
scanf("%d",&val);
x=search(val);
if(x==1)
printf("\n element found");
else
printf("\n element not found");
break;
case 6:
display();
break;
case 7:
exit(1);
break;
default:
printf("choose valid option\n");
}
}
}
 
Comments
Post a Comment