Wednesday, 5 December 2012

Doubly Linked List Program

 

//Program for the Doubly linked list//

#include<stdio.h>

#include<conio.h>

#include<alloc.h>

 

struct node

{

struct node *lptr;

struct node *rptr;

int data;

}*first=NULL;

 

void insert(int val)

{

struct node *new1,*curr;

new1=(struct node *)malloc(sizeof(struct node));

new1->data=val;

new1->rptr=new1->lptr=NULL;

if(first==NULL)

{

first=new1;

return;

}

curr=first;

while(curr->rptr!=NULL)

{

curr=curr->rptr;

}

new1->lptr=curr;

curr->rptr=new1;

}

void display()

{

struct node *curr;

if(first==NULL)

{

printf("\n link list is empty");

return;

}

curr=first;

while(curr!=NULL)

{

printf("%d-->",curr->data);

curr=curr->rptr;

}

}

void delnode(int val)

{

struct node *curr;

if(first==NULL)

{

printf("\n link list is empty");

return;

}

curr=first;

if(curr->data==val)

{

first=first->rptr;

free(curr);

first->lptr=NULL;

return;

}

while(curr->data!=val && curr!=NULL)

{

curr=curr->rptr;

}

if(curr==NULL)

{

printf("\n value not found");

return;

}

curr->lptr->rptr=curr->rptr;

curr->rptr->lptr=curr->lptr;

free(curr);

}

void insertaft(int val,int key)

{

struct node *curr,*new1;

if(first==NULL)

{

printf("\n link list is empty");

return;

}

new1=(struct node*)malloc(sizeof(struct node));

new1->data=val;

new1->lptr=new1->rptr=NULL;

curr=first;

while(curr->data!=key && curr!=NULL)

{

curr=curr->rptr;

}

if(curr==NULL)

{

printf("\n key not found");

return;

}

new1->rptr=curr->rptr;

curr->rptr=new1;

new1->lptr=curr;

new1->rptr->lptr=new1;

}

void insertbfr(int val,int key)

{

struct node *new1,*curr;

new1=(struct node*)malloc(sizeof(struct node));

new1->data=val;

new1->lptr=new1->rptr=NULL;

curr=first;

while(curr->data!=key && curr!=NULL)

{

curr=curr->rptr;

}

if(curr==NULL)

{

printf("\n key not found");

return;

}

curr->lptr->rptr=new1->rptr;

curr->lptr->rptr=new1;

curr->lptr=new1->lptr;

new1=curr->lptr;

}

void main()

{

int ch,val,key;

clrscr();

do

{

printf("\n!!-----MENU-----!!");

printf("\n 1.insert      ");

printf("\n 2.display    ");

printf("\n 3.delete   ");

printf("\n 4.insert after ");

printf("\n 5.insert before" );

printf("\n 6.exit  ");

printf("\n-------------------");

printf("\n enter the choice");

scanf("%d",&ch);

if(ch==1)

{

printf("\n enter any number");

scanf("%d",&val);

insert(val);

}

else if(ch==2)

{

printf("\n");

display();

}

else if(ch==3)

{

printf("\n enter tany value delet ");

scanf("%d",&val);

delnode(val);

}

else if(ch==4)

{

printf("\n enter the key");

scanf("%d",&key);

printf("\n enter the value");

scanf("%d",&val);

insertaft(val,key);

}

else if(ch==5)

{

printf("\n enter the key");

scanf("%d",&key);

printf("\n enter the value");

scanf("%d",&val);

insertbfr(val,key);

}

else if(ch==6)

{

printf("\n good bye");

break;

}

else

{

printf("\n invalid choice");

}

}while(ch!=6);

getch();

}

 

 

 

No comments:

Post a Comment