aboutsummaryrefslogtreecommitdiff
path: root/backend/List.hpp
blob: d6c7738980557344d16f9fee87886200640c5a80 (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
#pragma once

#include <stdlib.h>

template <typename T>
struct ListLink {
	ListLink<T> * prev;
	ListLink<T> * next;
	T value;
};

template<typename T>
class List {
public:
	size_t size() { return this->length; }

	void push_back(T el) {
		ListLink<T> * link = static_cast<ListLink<T> *>(malloc(sizeof(ListLink<T>)));
		link->prev = this->head;
		link->next = nullptr;
		link->value = el;
		if (this->head != nullptr) this->head->next = link;
		if (this->head == nullptr) this->tail = link;
		this->head = link;
		this->length++;
	}

	void pop_back() {
		if (this->head == nullptr) return; // empty list

		ListLink<T> * secondlast = this->head->prev;
		if (secondlast != nullptr)
			secondlast->next = nullptr;
		free(this->head);
		if (this->tail == this->head)
			this->tail = nullptr;
		this->head = secondlast;

		this->length--;
	}

	void clear() {
		ListLink<T> * link = this->tail;
		while (link != nullptr) {
			ListLink<T> * next = link->next;
			free(link);
			link = next;
		}
		this->head = nullptr;
		this->tail = nullptr;
		this->length = 0;
	}

	T & operator [] (size_t index) {
		ListLink<T> * link = this->tail;
		for (size_t i = 0; i < index; i++)
			link = link->next;
		return link->value;
	}

private:
	ListLink<T> * head = nullptr;
	ListLink<T> * tail = nullptr;
	size_t length = 0;
};