-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDoubleLinkedList.h
123 lines (98 loc) · 2.07 KB
/
DoubleLinkedList.h
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
114
115
116
117
118
119
120
#ifndef DOUBLELINKEDLIST_H__
#define DOUBLELINKEDLIST_H__
#include <iosfwd>
template <class T>
struct DoubleNode
{
DoubleNode (DoubleNode<T> *Prev, DoubleNode<T> *Next, T Value) : prev(Prev), next(Next), value(Value) {}
DoubleNode<T> *prev, *next;
T value;
};
template <class T>
class DoubleLinkedList
{
public:
DoubleLinkedList () :root(&root,&root,T()), initialized(0), current(&root) {}
~DoubleLinkedList();
void append(T value);
void print();
DoubleNode<T> root;
// Move and get the value.
T next();
T prev();
// Returns the value without moving.
T read();
T read_next();
T read_prev();
private:
bool initialized;
DoubleNode<T> *current;
};
// Always appends to the end of the chain (before the root, which closes the cycle)
template <class T>
void DoubleLinkedList<T>::append(T value)
{
if (initialized == false)
{
root.value = value;
initialized = true;
}
else
{
DoubleNode<T> *node = new DoubleNode<T>(root.prev, &root, value);
root.prev->next = node;
root.prev = node;
}
}
template <class T>
DoubleLinkedList<T>::~DoubleLinkedList()
{
DoubleNode<T> *node = root.next, *next_node;
while (node != &root)
{
next_node = node->next;
delete node;
node = next_node;
}
}
template <class T>
T DoubleLinkedList<T>::read()
{
return current->value;
}
template <class T>
T DoubleLinkedList<T>::next()
{
current = current->next;
return current->value;
}
template <class T>
T DoubleLinkedList<T>::prev()
{
current = current->prev;
return current->value;
}
template <class T>
T DoubleLinkedList<T>::read_next()
{
return current->next->value;
}
template <class T>
T DoubleLinkedList<T>::read_prev()
{
return current->prev->value;
}
template <class T>
void DoubleLinkedList<T>::print()
{
DoubleNode<T> *node = root.next;
std::cout << "Fwd: ";
std::cout << root.value << " ";
while (node != &root) // More than one node.
{
std::cout << node->value << " ";
node = node->next;
}
std::cout << std::endl;
}
#endif // DOUBLELINKEDLIST_H__