-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcirclinkedlist.h
154 lines (142 loc) · 3.19 KB
/
circlinkedlist.h
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
#include <iostream>
template <typename T>
struct Node
{
public:
T val;
Node* next;
Node()
{
this->val=T{};
this->next=NULL;
}
Node(T val)
{
this->val=val;
this->next=NULL;
}
};
//Circularly Linked List
// works as a stack
template <typename T>
class LinkedList
{
private:
Node<T>* root;
Node<T>* prev;
int size;
public:
LinkedList()
{
this->root=NULL;
this->prev=NULL;
this->size=0;
}
~LinkedList()
{
if(this->size>0)
{
Node<T>* node=this->root;
for(int i=0;i<this->size;i++)
{
Node<T>* to_del=node;
node=node->next;
delete to_del;
}
}
}
int get_size()
{
return this->size;
}
bool push(T val)
{
if(this->size==0)
this->root=new Node<T>(val);
else
{
Node<T>* node=new Node<T>(val);
if(this->size==1)
node->next=this->root;
else
node->next=this->root->next;
this->root->next=node;
this->prev=this->root;
this->root=node;
}
this->size++;
return true;
}
bool insert(T val, int index)
{
if(index<0||index>this->size)
{
std::cout<<"Invalid Operation"<<std::endl;
return false;
}
if(index==this->size)
return push(val);
Node<T>* new_node=new Node<T>(val);
Node<T>* node=this->root;
for(int i=0;i<index;i++)
node=node->next;
if(this->size==1)
new_node->next=node;
else
new_node->next=node->next;
node->next=new_node;
this->size++;
return true;
}
T pop()
{
if(this->size==0)
{
std::cout<<"Invalid Operation"<<std::endl;
return T{};
}
T to_del=this->root->val;
if(this->size>1)
this->prev->next=this->root->next;
delete this->root;
this->size--;
return to_del;
}
T remove(int index)
{
if(index<0||index>=this->size)
{
std::cout<<"Invalid Operation"<<std::endl;
return T{};
}
if(index==this->size-1)
return pop();
Node<T>* node=this->root->next;
Node<T>* prev_node=this->root;
for(int i=0;i<index;i++)
{
node=node->next;
prev_node=prev_node->next;
}
prev_node->next=node->next;
T to_del=node->val;
delete node;
this->size--;
return to_del;
}
void display()
{
if(this->size==1)
{
std::cout<<this->root->val<<std::endl;
return;
}
Node<T>* node=this->root;
for(int i=0;i<this->size;i++)
{
node=node->next;
std::cout<<node->val<<" ";
}
std::cout<<std::endl;
}
};