Search This Blog

Tuesday 27 October 2015

Doubly linked list (all 8 operations)

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int info;
struct node *prev;
struct node *next;
};
struct node *head=NULL;
struct node *tail=NULL;
void insert_begin(int item)
{
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
p->info=item;
if (head==NULL)
{
p->prev=NULL;
p->next=NULL;
head=p;
tail=p;
}
else
{
p->prev=NULL;
head->prev=p;
p->next=head;
head=p;
}}
void insert_end(int item)
{
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
p->info=item;
if (head==NULL)
{
p->prev=NULL;
p->next=NULL;
head=p;
tail=p;
}
else
{
p->next=NULL;
tail->next=p;
p->prev=tail;
tail=p;
}}
void delete_begin()
{
struct node *p;
if (head==NULL)
printf("list is empty");
else
{
 if(head==tail)
  {
  p=head;
  head=NULL;
  tail=NULL;
  }
  else
  {
  p=head;
  head=head->next;
  head->prev=NULL;
  }
  printf("\ndeleted element is %d",p->info);
  free(p);
 }}
void delete_end()
{
struct node *p;
if (head==NULL)
printf("list is empty");
else
{
 if(head==tail)
  {
  p=head;
  head=NULL;
  tail=NULL;
  }
  else
  {
   p=tail;
   tail=tail->prev;
   tail->next=NULL;
  }
  printf("\ndeleted element is %d",p->info);
  free(p);
 }}
void display()
{
int i;
struct node *p;
p=head;
if(head==NULL)
printf("empty list");
else
{
 while(p!=NULL)
 {
  printf("%d",p->info);
  p=p->next;
 }}}
void main()
{
int ch,item;
clrscr();
printf("\n1.insert begin\n2.insert end\n3.delete begin\n4.delete end\n5.display\n6.exit");
do
{
 printf("\nenter your choice");
 scanf("%d",&ch);
 switch(ch)
 {
 case 1:printf("eneter value ");
                scanf("%d",&item);
                insert_begin(item);
                break;
 case 2:printf("eneter value ");
                scanf("%d",&item);
                insert_end(item);
                break;
 case 3:delete_begin();
                break;
 case 4:delete_end();
                break;
 case 5:display();
                break;
 case 6:exit(0);
 default:printf("invalid option");
 }}while(ch!=6);
getch();

}

No comments:

Post a Comment