-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list.cpp
executable file
·78 lines (61 loc) · 1.32 KB
/
linked_list.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
#include <iostream>
#include <optional>
class Node
{
public:
int data;
std::optional<Node *> next;
Node(int d) : data(d), next(nullptr) {}
};
class LinkedList
{
public:
std::optional<Node *> head;
std::optional<Node *> tail;
LinkedList() = default;
LinkedList(Node *h);
void print() const;
void append(int data);
Node *&getHead();
};
LinkedList::LinkedList(Node *h) : head(h), tail(h) {}
Node *&LinkedList::getHead()
{
return head.value();
}
void LinkedList::print() const
{
Node *current = head.value_or(nullptr);
while (current != nullptr)
{
std::cout << current->data << " -> ";
current = current->next.value();
}
std::cout << "None" << std::endl;
}
void LinkedList::append(int data)
{
Node *new_node = new Node(data);
if (!head.has_value())
{
head = new_node;
tail = new_node;
}
else
{
tail.value()->next = new_node;
tail = new_node;
}
}
int main()
{
LinkedList list;
list.append(10);
list.append(20);
list.append(30);
list.print(); // Output: 10 -> 20 -> 30 -> None
std::cout << list.getHead() << std::endl;
std::cout << list.head.value() << std::endl;
greet();
return 0;
}