Repository navigation
Expand file tree
/
Copy pathbonusassignment1.2.cpp
More file actions
84 lines (73 loc) · 1.76 KB
/
Copy pathbonusassignment1.2.cpp
File metadata and controls
84 lines (73 loc) · 1.76 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
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int val) {
data = val;
next = nullptr;
}
};
class CircularLinkedList {
private:
Node* head;
public:
CircularLinkedList() {
head = nullptr;
}
void InsertSorted(int x) {
Node* newNode = new Node(x);
if (head == nullptr) {
head = newNode;
newNode->next = head;
return;
}
if (head->data >= x) {
Node* last = head;
while (last->next != head) {
last = last->next;
}
newNode->next = head;
last->next = newNode;
head = newNode;
return;
}
Node* current = head;
while (current->next != head && current->next->data < x) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
void PrintList() {
if (head == nullptr) return;
Node* temp = head;
do {
cout << temp->data << " ";
temp = temp->next;
} while (temp != head);
cout << endl;
}
void MakeNull() {
if (head == nullptr) return;
Node* current = head;
Node* nextNode;
do {
nextNode = current->next;
delete current;
current = nextNode;
} while (current != head);
head = nullptr;
}
};
int main() {
CircularLinkedList list;
list.InsertSorted(5);
list.InsertSorted(2);
list.InsertSorted(8);
list.InsertSorted(3);
list.PrintList();
list.MakeNull();
return 0;
}