Monday, June 11, 2012

Circular Doubly linked list in C Programming


Today I will discuss on circular doubly linked list.

Program on circular doubly linked list without any header node.

 #include< stdio.h >
#include< stdlib.h >
struct list
{
int num;
struct list *next;
struct list *prev;
};
struct list *node;
void create(struct list *n)
{
char ch;
node=n;
printf("\nWant to create location(y/n):-");
scanf("%c",&ch);
fflush(stdin);
while(ch!='n')
{
fflush(stdin);
node->next=(struct list *)malloc(sizeof(struct list));
node->next->prev=node;
node=node->next;
printf("\Enter value:-");
scanf("%d",&node->num);
fflush(stdin);
printf("\Any more (y/n)");
scanf("%c",&ch);
}
node->next=n;
n->prev=node;
}
void display(struct list *n)
{
node=n->next;
while(node!=n)
{
printf("%d\n",node->num);
node=node->next;
}
}
void main()
{
struct list *start=NULL;
clrscr();
create(start);
printf("Now display the value of the circular lists:-\n");
display(start);
getch();
}


 Another program on circular doubly linked list with header node


In this program insertion of new created node at any location of the circular doubly linked list can be done.

#include< stdio.h >
#include< stdlib.h >
struct list
{
int num;
struct list *next;
struct list *prev;
};
struct list *node;
void create(struct list *n)
{
char ch;
node=n;
printf("\nWant to create location(y/n):-");
scanf("%c",&ch);
fflush(stdin);
while(ch!='n')
{
fflush(stdin);
node->next=(struct list *)malloc(sizeof(struct list));
node->next->prev=node;
node=node->next;
printf("\Enter value:-");
scanf("%d",&node->num);
fflush(stdin);
printf("\Any more (y/n)");
scanf("%c",&ch);
}
node->next=n;
n->prev=node;
}
void display(struct list *n)
{
node=n->next;
while(node!=n)
{
printf("%d\n",node->num);
node=node->next;
}
}
void insert(struct list *n)
{
struct list *node,*new1;
int c=1,count;
node=n;
new1=(struct list*)malloc(sizeof(struct list));
printf("\nEnter the location where the new location will be inserted:");
scanf("%d",&count);
printf("\Enter value:-");
scanf("%d",&new1->num);
do
{
if(c==count)
break;
node=node->next;
c++;
}while(node!=n);
new1->next=node->next;
node->next->prev=new1;
node->next=new1;
new1->prev=node;
}

void main()
{
struct list *start;
clrscr();
start=(struct list*)malloc(sizeof(struct list));
/* header node without any value */
create(start);
printf("Now display the value of the circular lists:-\n");
display(start);
insert(start);
printf("\nAfter insertion, the list is\n");
display(start);
getch();
}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner