forked from andy-thomason/double_linked_list
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
114 lines (92 loc) · 2.35 KB
/
main.cpp
File metadata and controls
114 lines (92 loc) · 2.35 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
112
113
#include <iostream>
// This is your
struct item {
// link to next item in the list or "head"
item *next;
// link to the previous item or "head"
item *prev;
// the value in the list
int value;
item(int value=0) : value(value) {}
};
// The
class double_linked_list {
public:
// placeholder for you to replace.
item *Tail = nullptr;
// The head item is the first and last in the list.
// head <-> one <-> two <-> three <-> head
item head;
double_linked_list() {
// at the start, the head points to itself.CONSTRUCTOR
head.prev = head.next = &head;
}
item *insert(int value) {
item *new_item = new item(value);
new_item->prev = &head;
new_item->next = head.next; // fill this in
head.next->prev = new_item;
if (head.prev == &head)
{
head.prev =new_item;
}
// fill this in
head.next = new_item;
return new_item;
}
item *insert_after(item *prev, int value) {
item *next = prev->next;
item *new_item = new item(value);
new_item->prev = prev;
new_item->next = next; // fill this in
prev->next = new_item; // fill this in
next->prev = new_item; // fill this in
return new_item;
}
item *find(int value) {
// write a loop here to return the first element with this value
item *index = head.next;
while (index != &head)
{
if ((index->value) == value)
return index;
index = index->next;
}
return nullptr;
}
item *get_first() {
return head.next;
}
void remove(item *victim) {
item *prev = victim->prev;
item *next = victim->next;
victim->prev = nullptr; // fill this in
victim->next = nullptr; // fill this in
prev->next = next; // fill this in
next->prev = prev; // fill this in
}
void dump(std::ostream &os) {
for (item *it = head.next; it != &head; it = it->next) {
os << "item " << it << " has value " << it->value << "\n";
}
}
// unit test
void unit_test() {
double_linked_list my_list;
my_list.insert(1);
my_list.insert(2);
my_list.insert(3);
my_list.insert(4);
my_list.dump(std::cout);
auto two = my_list.find(2);
my_list.remove(two);
my_list.dump(std::cout);
auto three = my_list.find(3);
my_list.insert_after(three, 33);
my_list.dump(std::cout);
}
};
int main() {
double_linked_list my_list;
my_list.unit_test();
}