summaryrefslogtreecommitdiff
path: root/Source/Library/Common/SimpleList.class.h
blob: 58061554cec9fce6ec29cfe415fa390b79d8f8db (plain) (blame)
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
#ifndef DEF_SIMPLELIST_CLASS_H
#define DEF_SIMPLELIST_CLASS_H

#include <common.h>

/* This class implements a singly linked list. It is also used to represent one of its elements. */

template <typename T>
class SimpleList {
	protected:
	T m_value;
	SimpleList<T>* m_next;

	public:
	SimpleList(const T& value, SimpleList<T>* next = 0) : m_value(value), m_next(next) {}
	~SimpleList() {
		if (m_next != 0)
			delete m_next;
	}

 	T& v() { return m_value; }
	T& operator* () { return m_value; }

	SimpleList<T>* cons(const T& value) {
		return new SimpleList<T>(value, this);
	}

	SimpleList<T>* addAtEnd(const T& value) {
		if (this == 0) {
			return new SimpleList<T>(value);
		} else {
			if (m_next == 0) {
				m_next = new SimpleList<T>(value);
				return m_next;
			} else {
				return m_next->addAtEnd(value);
			}
		}
	}

	SimpleList<T>* next() {
		return m_next;
	}

	SimpleList<T>* last() {
		if (m_next == 0) return this;
		return m_next->last();
	}

	SimpleList<T>* delThis() {
		SimpleList<T>* ret = m_next;
		Mem::free(this);
		return ret;
	}

	void delNext() {
		if (m_next == 0) return;
		SimpleList<T>* temp = m_next;
		m_next = m_next->m_next;
		Mem::free(temp);
	}

	SimpleList<T>* removeOnce(const T& value) {
		if (this == 0) return 0;
		if (value == m_value) return delThis();
		for (SimpleList<T> *iter = this; iter->next() != 0; iter = iter->next()) {
			if (iter->next()->v() == value) {
				iter->delNext();
				break;
			}
		}
		return this;
	}

	bool isEnd() {
		return m_next == 0;
	}

	u32int size() {
		if (m_next == 0)
			return 1;
		return m_next->size() + 1;
	}
};

#endif