Friday, 6 January 2017

Double Linked List program in exam point of view with different functions

#include <stdio.h>
struct node
{
int data;
struct node *next,*back;
};

struct node *head,*tail,*c;
deleteend();
deletebeg();
deleteend();
insertmiddle(int);
insertend(int);
insertbeg(int);
display();
reverseDisplay();
main()
{
int n,i,value;
create();
display();
printf("\nenter a value to insert at beginning");
scanf("%d",&value);
insertbeg(value);
display();
printf("\nenter a value to insert");
scanf("%d",&value);
insertmiddle(value);
display();
deletebeg();
printf("\nafter deleting first node\n");
display();
deletemiddle();
printf("\nafter deleting\n");
display();
printf("\nafter deleting last node\n");
deleteend();
display();
reverseDisplay();

}
create()
{
int value,opt;
while(1)
{
printf("Press 1 to continue and Press 0 to stop");
scanf("%d",&opt);
if(opt == 1)
{
printf("\nenter a value");
scanf("%d",&value);
struct node *newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=value;
if(head == NULL)
{
newnode->next=NULL;
newnode->back=NULL;
head=tail=newnode;

}
else
{
tail->next=newnode;
newnode->back=tail;
newnode->next=NULL;
tail=newnode;
}
}
else
return;
}
}
insertmiddle(int value)
{
int pos,i=1;
struct node *newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=value;
printf("enter the position at which u want to insert");
scanf("%d",&pos);
c=head;
while(i<pos && c!=NULL)
{

c=c->next;
i++;
}

newnode->next=c;
newnode->back=c->back;
c->back->next=newnode;
c->back=newnode;

}
insertbeg(int value)
{
struct node *newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=value;
if(head == NULL)
{
newnode->next=NULL;
newnode->back=NULL;
head=tail=newnode;

}
else
{
newnode->back=NULL;
newnode->next=head;
head->back=newnode;
head=newnode;
}
}

deletebeg()
{
c=head;
head->next->back=NULL;
head=head->next;
free(c);
}
deletemiddle()
{
int pos,i=1;
printf("enter the position at which u want to delete");
scanf("%d",&pos);
c=head;
while(i<pos)
{
c=c->next;
i++;
}
c->next->back=c->back;
c->back->next=c->next;
free(c);
}
deleteend()
{
c=tail;
tail=tail->back;
tail->next=NULL;
free(c);
}
display()
{
c=head;
if(head==NULL)
{
printf("list is empty");
}
else
{
while(c!=NULL)
{
printf("%d<->",c->data);
c=c->next;
}
}
}
reverseDisplay()
{
printf("\n Values of DDL in reverse order\n");
for(c=tail;c!=NULL;c=c->back)
printf("\t%d\t",c->data);
}


Output:



No comments:

Post a Comment