Monday, 9 January 2017

Doubly circular linked list C program

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

struct node *head,*c;
deleteend();
deletebeg();
deleteend();
insertmiddle(int);
insertend(int);
insertbeg(int);
display();
create();
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();
}
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)
{
head=newnode;
newnode->next=head;
newnode->back=head;
}
else
{
newnode->next=head;
newnode->back=head->back;
newnode->back->next=newnode;
head->back=newnode;
}
}
else
return;
}
}
insertmiddle(int value)
{
int pos,i=1;
struct node *newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=value;
printf("\nenter the position at which u want to insert\n");
scanf("%d",&pos);
c=head;
while(i<pos)
{

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)
{
head=newnode;
newnode->next=head;
newnode->back=head;

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

deletebeg()
{
c=head;
head->next->back=head->back;
head->back->next=head->next;
head=head->next;
free(c);
}
deletemiddle()
{
int pos,i=1;
printf("\nenter the position at which u want to delete\n");
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=head->back;
head->back=head->back->back;
head->back->next=head;
free(c);
}
display()
{
c=head;
if(head==NULL)
{
printf("list is empty");
}
else
{
do
{
printf("%d<->",c->data);
c=c->next;
}while(c!=head);
}
}

Output:

No comments:

Post a Comment