-
Notifications
You must be signed in to change notification settings - Fork 2
/
CircularLinkedList(haven't comprehend).cpp
107 lines (101 loc) · 2.06 KB
/
CircularLinkedList(haven't comprehend).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
#include "DataStructAndAlgorithm.h"
class LinkedListNode {
public:
int data;
LinkedListNode *next = NULL;
LinkedListNode(int _data) {
data = _data;
}
};
class CircularLinkedList {
public:
LinkedListNode* find(int index) {
if (head == NULL) {
return NULL;
}
LinkedListNode *current_node = head->next;
int count = 0;
while (current_node != head&&count != index) {
current_node = current_node->next;
count++;
}
if (count == index) {
return current_node;
}
return NULL;
}
void insert(LinkedListNode *node, int index) {
if (head == NULL) {
head = node;
head->next = head;
return;
}
if (index == 0) {
node->next = head->next;
head->next = node;
return;
}
LinkedListNode *pre_node = find(index - 1);
if (pre_node != NULL) {
node->next = pre_node->next;
pre_node->next = node;
}
if (node == head->next) {
head = node;
}
}
void remove(int index) {
if (head == NULL) {
return;
}
LinkedListNode *delete_node = NULL;
if (index == 0) {
delete_node = head->next;
head->next = delete_node->next;
delete delete_node;
return;
}
LinkedListNode *pre_node = find(index - 1);
if (!pre_node) {
return;
}
if (pre_node == head) {
return;
}
delete_node = pre_node->next;
pre_node->next = delete_node->next;
if (delete_node == head) {
head = pre_node;
}
delete delete_node;
}
void reverse() {
if (head == NULL) {
return;
}
LinkedListNode *current_node = head->next;
LinkedListNode *next_node = NULL;
LinkedListNode *origin_head = head;
LinkedListNode *origin_next = head->next;
do {
next_node = current_node->next;
current_node->next = head;
head = current_node;
current_node = next_node;
} while (head != origin_head);
head = origin_next;
}
void output() {
if (head == NULL) {
cout << "Linked List is NULL" << endl;
}
LinkedListNode *current_node = head->next;
do {
cout << current_node->data << " ";
current_node = current_node->next;
} while (current_node != head->next);
cout << endl;
}
private:
LinkedListNode *head = NULL;
};