Help Me/Question How To Implement Doubly Circular Linked List?

steve taylor

Yellow Belt
Doubly linked list maintain two pointers between every pain of the nodes. One link point to next node and another link point to previous node .
In doubly circular linked list last node and first node also maintain the link for point next node and the previous node.
How to implement it in C programming.
 

krishatg

Yellow Belt
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
struct Node *prev;
}node;
void insert(node *p, int data)
{
/* Iterate through the list till we encounter the last node.*/
while(p->next!=NULL)
{
p = p -> next;
}
/* Allocate memory for the new node and put data in it.*/
p->next = (node *)malloc(sizeof(node));
(p->next)->prev = p;
p = p->next;
p->data = data;
p->next = NULL;
}
int find(node *p, int key)
{
p = p -> next; //First node is dummy node.

while(p!=NULL)
{
if(p->data == key) //key is found.
{
return 1;
}
p = p -> next;//Search in the next node.
}

return 0;
}
void delete(node *p, int data)
{

while(p->next!=NULL && (p->next)->data != data)
{
p = p -> next;
}
if(p->next==NULL)
{
printf("Element %d is not present in the list\n",data);
return;
}

node *t;
t = p -> next;

p->next = t->next;
t->prev = p;

free(t);


return;
}
void print(node *p)
{
if(p==NULL)
{
return;
}
printf("%d ",p->data);
print(p->next);
}
int main()
{


node *start,*t;
start = (node *)malloc(sizeof(node));
t = start;
t -> next = NULL;
t -> prev = NULL;

printf("1. Insert\n");
printf("2. Delete\n");
printf("3. Print\n");
printf("4. Find\n");
while(1)
{
int q;
scanf("%d",&q);
if(q==1)
{
int data;
scanf("%d",&data);
insert(start,data);
}
else if(q==2)
{
int data;
scanf("%d",&data);
delete(start,data);
}
else if(q==3)
{
printf("The list is ");
print(start->next);
printf("\n");
}
else if(q==4)
{
int data;
scanf("%d",&data);
int status = find(start,data);
if(status)
{
printf("Element Found\n");
}
else
{
printf("Element Not Found\n");

}
}
}


}
 

krishatg

Yellow Belt
In this first off all it will ask for option that either you want to insert delete find or print. According to option it will call required function and perform operation. For first time you need to call insert operation. only then you can see working of other operations.
 
Top