-
Notifications
You must be signed in to change notification settings - Fork 0
/
CircularDoublyLinkedList.cpp
165 lines (153 loc) · 2.79 KB
/
CircularDoublyLinkedList.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node *next, *prev;
Node(Node *p=NULL, int val=0, Node *n=NULL){
data = val;
next = n;
prev =p;
}
};
class LinkedList{
Node *head,*tail;
public:
LinkedList(){
head = tail = NULL;
}
~LinkedList(){
while(!isEmpty()){
removeHead();
}
}
bool isEmpty(){
if(head == NULL){
return true;
}else{
return false;
}
}
void addHead(int n){
if(isEmpty()){
head = new Node(NULL,n,NULL);
tail = head;
head->next = head->prev = head;
}else{
Node *p = new Node(tail,n,head);
head->prev = tail->next = p;
head = p;
}
}
void addTail(int n){
if(isEmpty()){
addHead(n);
}else{
Node *p = new Node(tail,n,head);
tail->next = p->prev;
p->next = head->prev;
tail = p;
}
}
void insert(int val, int pos){
int count = 0;
for(Node *p = head; p!=NULL; p = p->next){
count++;
}
if(pos<1 || pos > count+1){
cout << "wrong input";
}else if(pos == 1){
addHead(val);
}else if(pos == count+1){
addTail(val);
}else{
Node *p = head, *q;
for(int i=0; i<pos; i++){
q=p;
p = p->next;
}
Node *r = new Node(q,val,p);
q->next = p->prev = r;
}
}
void traverse(){
if(isEmpty()){
cout << "EMPTY";
}else{
Node *p = head;
do{
cout << p->data << endl;
p = p->next;
}while(p!=head);
}
}
void search(int n){
int flag = 0;
for (Node *p = head; p!=NULL; p= p->next){
if(p->data ==n){
flag++;
cout << "found";
break;
}
if(flag==0){
cout << "Not found";
}
}
}
int removeHead(){
if(isEmpty()){
cout << "LL is empty";
return 0;
}else if(head == tail){
int temp = head->data;
delete head;
head = tail = NULL;
return temp;
}else{
int temp = head->data;
Node *p = head;
head = head->next;
delete p;
head->prev = tail;
return temp;
}
}
int removeTail(){
if(isEmpty()){
cout << "LL is empty";
}else if(head == tail){
removeHead();
}else{
int temp = tail->data;
Node *p = tail;
tail->next = head;
delete p;
head->prev=tail;
return temp;
}
}
int deleteKey(int n){
if(isEmpty()){
cout << "LL is empty";
}else if(head->data == n){
return removeHead();
}else if(tail->data == n){
return removeTail();
}else{
Node *p = head->next;
while(p->data!=n && p!=NULL){
p = p->next;
}if(p == NULL){
cout << "not found";
return 0;
}else{
Node *q = p->prev;
Node *r = p->next;
delete p;
q->next = r;
r->prev = q;
return n;
}
}
}
};