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