-
Notifications
You must be signed in to change notification settings - Fork 0
/
circular_linked_list.cpp
85 lines (67 loc) · 1.37 KB
/
circular_linked_list.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
#include <iostream> // for cout
#include <stdexcept> // for runtime_error
using namespace std;
struct
Node{
int value;
Node *next=nullptr;
Node(int value) : value(value)
{
}
Node(int value, Node *next) : value(value), next(next)
{
}
};
class CircLinkedList
{
private:
Node *head = nullptr;
public:
CircLinkedList(){
}
void append(int value)
{
Node *node = new Node{value};
if (head==nullptr){
head = node;
node -> next=head;
return;
}
Node *current;
current = head;
while (current->next != head){
current = current->next;
}
current->next=node;
node -> next = head;
}
void print() {
Node* current = head;
cout << "[";
while (current->next != head) {
cout << current->value;
cout << ", ";
current = current->next;
}
cout << current->value << "]" << endl;
}
int& operator[](int index) {
return get_node(index)->value;
}
Node* get_node(int index) {
Node* current = head;
for (int i=0; i<index; i++) {
current = current->next;
}
return current;
}
};
int main(){
CircLinkedList clist;
clist.append(0);
clist.append(2);
clist.append(4);
cout<< clist[1] <<endl;
clist.print();
return 0;
}