-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircular_list.cpp
More file actions
111 lines (102 loc) · 2.03 KB
/
circular_list.cpp
File metadata and controls
111 lines (102 loc) · 2.03 KB
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
//Circular Linked List
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
Node* next;
int data;
Node(int x) {
next = nullptr;
data = x;
}
};
void insertNode(Node**head, int data, int index) {
Node* new_node = new Node(data);
if (*head == nullptr) {
*head = new_node;
new_node->next = *head;
}
else if (index == 0) {
new_node->next = *head;
Node* cur = *head;
while (cur->next != *head) {
cur = cur->next;
}
cur->next = new_node;
*head = new_node;
}
else {
Node*cur = *head;
Node*pre = nullptr;
while (index != 0 && cur->next != *head) {
pre = cur;
cur = cur->next;
index--;
}
if (cur->next == *head) {
cur->next = new_node;
new_node->next = *head;
}
else {
pre->next = new_node;
new_node->next = cur;
}
}
}
int deleteNode(Node** head, int index) {
if (*head == nullptr) {
return INT_MIN;
}
Node*cur = *head;
if (index == 0) {
int data = (*head)->data;
while (cur->next != *head) {
cur = cur->next;
}
cur->next = (*head)->next;
delete *head;
*head = cur->next;
return data;
}
else {
Node*pre = nullptr;
while (index != 0 && cur->next != *head) {
pre = cur;
cur = cur->next;
index--;
}
pre->next = cur->next;
int data = cur->data;
delete cur;
return data;
}
}
void printCircularList(Node* head) {
Node*cur = head;
while (head != nullptr ) {
cout << head->data << " ";
if (head->next != nullptr && head->next == cur) {
break;
}
head = head->next;
}
cout << endl;
}
int main() {
Node*head = nullptr;
//Inserting At Start
insertNode(&head, 12, 0);
insertNode(&head, 15, 0);
printCircularList(head);
insertNode(&head, 18, 2);
printCircularList(head);
insertNode(&head, 11, 3);
printCircularList(head);
insertNode(&head, 5, 1);
printCircularList(head);
deleteNode(&head, 12); //Will delete last element before head node
deleteNode(&head, 0);
deleteNode(&head, 0);
printCircularList(head);
return 0;
}