Skip to content

Commit 41d4ecd

Browse files
authored
Merge pull request #431 from Soumyajit2411/master
Double circular linked list implementation
2 parents f6cf132 + bf0c916 commit 41d4ecd

File tree

1 file changed

+136
-0
lines changed

1 file changed

+136
-0
lines changed

double_circular_linkedlist.cpp

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
#include<iostream>
2+
#include<stdlib.h>
3+
using namespace std;
4+
5+
struct node
6+
{
7+
int data;
8+
struct node *next;
9+
struct node *prv;
10+
};
11+
12+
void create(struct node **h)
13+
{
14+
int n,i;
15+
printf("How many elements you want to enter: ");
16+
scanf("%d",&n);
17+
struct node *ptr=NULL;
18+
for(i=0;i<n;i++)
19+
{
20+
struct node *cur=(struct node *)malloc(sizeof(struct node));
21+
cur->data=rand()%10;
22+
cur->next=NULL;
23+
cur->prv=NULL;
24+
25+
if(*h==NULL)
26+
{
27+
*h=cur;
28+
cur->next=cur->prv=cur;
29+
ptr=cur;
30+
}
31+
else
32+
{
33+
cur->prv=ptr;
34+
ptr->next=cur;
35+
cur->next=*h;
36+
ptr=cur;
37+
}
38+
}
39+
40+
}
41+
42+
void display(struct node *h)
43+
{
44+
struct node *cur;
45+
printf("linked list:\t");
46+
for(cur=h;cur->next!=h;cur=cur->next)
47+
{
48+
printf("%d\t",cur->data);
49+
}
50+
printf("%d",cur->data);
51+
}
52+
53+
void insert(struct node **h,int x,int p)
54+
{
55+
struct node *cur;
56+
struct node *ptr;
57+
cur=(struct node *)malloc(sizeof(struct node));
58+
cur->data=x;
59+
cur->next=cur->prv=NULL;
60+
61+
if(*h==NULL)
62+
{
63+
*h=cur;
64+
cur->next=cur->prv=cur;
65+
}
66+
else if(p==0)
67+
{
68+
cur->next=*h;
69+
cur->prv=(*h)->prv;
70+
(*h)->prv->next=cur;
71+
(*h)->prv=cur;
72+
*h=cur;
73+
}
74+
else
75+
{
76+
ptr=*h;
77+
int i=1;
78+
while(i<p && ptr->next!=*h)
79+
{
80+
ptr=ptr->next;
81+
i++;
82+
}
83+
cur->next=ptr->next;
84+
cur->prv=ptr;
85+
ptr->next->prv=cur;
86+
ptr->next=cur;
87+
}
88+
89+
}
90+
91+
void del(struct node **h,int p)
92+
{
93+
struct node *ptr;
94+
struct node *cur;
95+
if(*h==NULL)
96+
{
97+
printf("EMPTY");
98+
}
99+
else if(p==0)
100+
{
101+
for(ptr=*h;ptr->next!=*h;ptr=ptr->next){}
102+
103+
ptr->next=(*h)->next;
104+
cur=*h;
105+
*h=(*h)->next;
106+
(*h)->next->prv=ptr;
107+
free(cur);
108+
}
109+
else
110+
{
111+
ptr=*h;
112+
int i=1;
113+
while(i<p && ptr->next!=*h)
114+
{
115+
cur=ptr;
116+
ptr=ptr->next;
117+
i++;
118+
}
119+
cur->next=ptr->next;
120+
ptr->next->prv=cur;
121+
free(ptr);
122+
}
123+
}
124+
125+
int main()
126+
{
127+
struct node *head=NULL;
128+
create(&head);
129+
display(head);
130+
insert(&head,2,6);
131+
display(head);
132+
printf("\n");
133+
del(&head,0);
134+
display(head);
135+
return 0;
136+
}

0 commit comments

Comments
 (0)