This repository was archived by the owner on Feb 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPersistent_Linked_List.cpp
More file actions
55 lines (55 loc) · 1.45 KB
/
Persistent_Linked_List.cpp
File metadata and controls
55 lines (55 loc) · 1.45 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
#include <iostream>
struct Node {
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
class PersistentLinkedList {
private:
Node* head;
public:
PersistentLinkedList() : head(nullptr) {}
PersistentLinkedList insert(int value) const {
PersistentLinkedList newList;
Node* newNode = new Node(value);
newList.head = copyList(head);
newNode->next = newList.head;
newList.head = newNode;
return newList;
}
void print() const {
Node* current = head;
std::cout << "List: ";
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
private:
Node* copyList(const Node* original) const {
if (original == nullptr) {
return nullptr;
}
Node* newHead = new Node(original->data);
Node* newCurrent = newHead;
const Node* current = original->next;
while (current != nullptr) {
newCurrent->next = new Node(current->data);
newCurrent = newCurrent->next;
current = current->next;
}
return newHead;
}
};
int main() {
PersistentLinkedList list1;
list1 = list1.insert(1);
list1 = list1.insert(2);
list1 = list1.insert(3);
list1.print();
PersistentLinkedList list2 = list1.insert(4);
list2.print();
list1.print();
return 0;
}