summaryrefslogtreecommitdiff
path: root/algo1w3/NAWLinkedList.cpp
blob: 06e46d8a0cf7cdecb25a46a8aa65f48b2b898569 (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
#include <iostream>

#include "NAWLinkedList.h"
#include "NAW.h"
#include "NAWLink.h"

NAWLinkedList::NAWLinkedList() { }

NAWLinkedList::~NAWLinkedList() {
	NAWLink* node = this->next;
	while (node != nullptr) {
		NAWLink* next = node->next;
		delete node; // also deletes NAW instance -> see NAWLink::~NAWLink
		node = next;
	}
}

void NAWLinkedList::addToStart(const NAW& value) {
	this->next = new NAWLink(value, this->next);
	this->size++;
}

NAWLink* NAWLinkedList::search(const NAW& value) const {
	NAWLink* node = this->next;
	while (node != nullptr) {
		if (node->value->compareTo(value) == 0) return node;
		node = node->next;
	}
	return nullptr;
}

NAWLink* NAWLinkedList::searchParent(const NAW& value) const {
	NAWLink* node = this->next;
	while (node != nullptr) {
		if (node->next == nullptr) return nullptr;
		if (node->next->value->compareTo(value) == 0) return node;
		node = node->next;
	}
	return nullptr;
}

void NAWLinkedList::showAll() const {
	std::cout << "/------------------------------\\" << std::endl;
	NAWLink* node = this->next;
	while (node != nullptr) {
		std::cout << *node->value; // prints values -> see operator << (std::ostream&, const NAW&)
		node = node->next;
		if (node != nullptr) std::cout << "              ----              " << std::endl;
	}
	std::cout << "\\------------------------------/" << std::endl;
}

NAWLink* NAWLinkedList::removeFirst(const NAW& value) {
	NAWLink* parent = searchParent(value);
	if (parent == nullptr) return nullptr;

	NAWLink* node = parent->next;
	parent->next = parent->next->next;

	return node;
}