-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEXP 4
87 lines (73 loc) · 1.75 KB
/
EXP 4
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
#include <iostream>
class Node {
public:
int data;
Node* next;
Node() : data(0), next(nullptr) {}
};
class LinkedList {
private:
Node* head;
public:
LinkedList() : head(nullptr) {}
void attach(int data) {
Node* newNode = new Node();
newNode->data = data;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
} else {
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
}
void detach() {
if (head == nullptr) {
std::cout << "List is empty. Cannot detach." << std::endl;
return;
}
Node* temp = head;
Node* prev = nullptr;
while (temp->next != nullptr) {
prev = temp;
temp = temp->next;
}
if (prev == nullptr) {
delete head;
head = nullptr;
} else {
prev->next = nullptr;
delete temp;
}
}
void traverse() {
if (head == nullptr) {
std::cout << "List is empty." << std::endl;
return;
}
Node* temp = head;
while (temp != nullptr) {
std::cout << temp->data << " ";
temp = temp->next;
}
std::cout << std::endl;
}
};
int main() {
LinkedList list;
list.attach(1);
list.attach(2);
list.attach(3);
list.traverse(); // Output: 1 2 3
list.detach();
list.traverse(); // Output: 1 2
list.detach();
list.traverse(); // Output: 1
list.detach();
list.traverse(); // Output: List is empty.
list.detach(); // Output: List is empty. Cannot detach.
return 0;
}