aboutsummaryrefslogtreecommitdiff
path: root/linked_list.cpp
blob: b30458c9055739fddccb0d8846af4519ce29e20b (plain)
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
#include "linked_list.h"

template <typename T>
llist<T>::llist () {
	this->length = 0;
	this->cur = this->head = new llink<T>;
	this->tail = new llink<T>;

	head->after  = tail;
	tail->before = head;
}

template <typename T>
llink<T>::~llink () {
	this.unlink();
}

template <typename T>
void llink<T>::unlink () {
	if (this->before != nullptr) this->before->after = this->after;
	if (this->after  != nullptr) this->after->before = this->before;
}

template <typename T>
void llist<T>::push(T* val) {
	auto l = new llink<T>(val);

	l->after    = FIRST(this);
	FIRST(this) = l;

	l->after->before = l;
	l->before        = this->head;

	++this->length;

	// TODO do I want to change that?
	this->cur = l;
}

template <typename T>
T& llist<T>::peek() {
	if (this->empty()) return nullptr;

	return FIRST(this)->value;
}

template <typename T>
T& llist<T>::pop() {
	if (this->empty()) return nullptr;

	llink<T>* frst = FIRST(this);
	frst.unlinke();

	T& retval = frst->value;
	--this->length;
	delete frst;

	return retval;
}

template <typename T>
void llist<T>::operator+= (llist<T>& other) {

	/* Link end of dest onto start of new__. */
	LAST(this)->after  = FIRST(other);
	FIRST(other)->before = LAST(this);

	/* Free the two now not needed end links.  */
	delete other->head;
	delete other->tail;

	/* Update dest with new__ tail ptr. */
	this->tail = other->tail;

	this->length += other->length;
}

// template <typename T>
// std::ostream& std::operator<<(std::ostream&, llist<T>) {
// o << '(';
// for (T t : list) {
//	o << t;
// }
// o << ')';
// }