forked from iamshubhamg/Leet-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoubly_circular_linkedList.cpp
137 lines (128 loc) · 2.98 KB
/
doubly_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
137
#include<iostream>
using namespace std;
struct Node{
struct Node *prev, *next;
int data;
}*head, *tail;
void createCircularDoublyLL(int arr[], int n){
if(n == 0){
head = tail = NULL;
}
else if(n == 1){
head = new Node;
head->data = arr[0];
head->next = NULL;
head->prev = NULL;
tail = head;
}
else{
struct Node *p, *last;
head = new Node;
head->data = arr[0];
head->next = NULL;
head->prev = NULL;
last = head;
for(int i=1; i<n; i++){
p = new Node;
p->data = arr[i];
p->next = NULL;
p->prev = last;
last->next = p;
last = p;
}
last->next = head;
head->prev = last;
tail = last;
}
}
void displayCircularDoublyLL(struct Node *p){
do{
cout << p->data << "->";
p = p->next;
}while(p != head);
cout << endl;
}
void reverseDisplayCircularDoublyLL(struct Node *p){
do{
cout << p->data << "->";
p = p->prev;
}while(p != tail);
cout << endl;
}
int Length(){
struct Node *p = head;
int count=0;
do{
count++;
p = p->next;
}while(p != head);
return count;
}
void insertNode(int pos, int value){
struct Node *p, *q;
if(pos == 0 || pos == Length()){
p = new Node;
p->data = value;
p->next = head;
p->prev = tail;
head->prev = p;
tail->next = p;
if(pos == 0){
head = p;
}
else if(pos+1 == Length()){
tail = p;
}
}
else{
p = new Node;
p->data = value;
q = head;
for(int i=1; i<pos; i++) q = q->next;
p->next = q->next;
p->prev = q;
q->next->prev = p;
q->next = p;
}
}
int deleteNode(int pos){
struct Node *p;
int x;
if(pos == 0){
p = head;
x = p->data;
head = head->next;
head->prev = p->prev;
p->prev->next = head;
}
else if(pos == Length()){
p = tail;
x = p->data;
tail = tail->prev;
tail->next = p->next;
p->next->prev = tail;
}
else{
p = head;
for(int i=1; i<pos; i++) p = p->next;
x = p->data;
p->prev->next = p->next;
p->next->prev = p->prev;
}
delete p;
return x;
}
int main(){
int arr[] = {1,2,3,4,5};
createCircularDoublyLL(arr, 5);
insertNode(0, 10);
insertNode(Length(), 20);
insertNode(4, 15);
cout << "The Element deleted is: " << deleteNode(Length()) << endl;
cout << "The Element deleted is: " << deleteNode(0) << endl;
cout << "The Element deleted is: " << deleteNode(4) << endl;
displayCircularDoublyLL(head);
reverseDisplayCircularDoublyLL(tail);
delete []head;
return 0;
}