-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList.cpp
117 lines (104 loc) · 2.6 KB
/
LinkedList.cpp
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
#include "LinkedList.h"
#include <iostream>
#include <vector>
LinkedList::LinkedList() {
head = nullptr;
}
LinkedList::~LinkedList() {
delete head;
}
LinkedList::LinkedList(LinkedList& other) {
this->head = nullptr;
Node* curNode = other.head;
// Traverse node and copy 1 by 1
while(curNode != NULL) {
this->append(curNode->tile);
curNode = curNode->next;
}
}
void LinkedList::print() {
Node* curNode = head;
// Base case, list is empty
if(head == nullptr) {
std::cout << "empty lol" << std::endl;
return;
}
// Traverse and print all nodes
while(curNode->next != NULL) {
std::cout << curNode->tile->letter << "-" << curNode->tile->value << ", ";
curNode = curNode->next;
}
// Final node to print without separating comma
std::cout << curNode->tile->letter << "-" << curNode->tile->value << std::endl;
}
void LinkedList::append(Tile* tile) {
Node* node = new Node(tile, NULL);
Node* curNode = head;
// Base case, list is empty
if(head == nullptr) {
head = node;
return;
}
// Traverse to end
while(curNode->next != NULL) {
curNode = curNode->next;
}
// Assign next node to appended node
curNode->next = node;
return;
}
Tile* LinkedList::pop() {
// Base case, list is empty
if(head == nullptr) {
return NULL;
}
// Assign head to next node and return removed tile
Tile* tile = head->tile;
head = head->next;
return tile;
}
Tile* LinkedList::remove(Letter letter) {
Node* curNode = head;
Node* prevNode = nullptr;
Tile* tile;
// Base case, list is empty
if(head == nullptr) {
return NULL;
}
// First letter found
if(head->tile->letter == letter) {
return this->pop();
}
// Traverse and search for letter
while(curNode != NULL) {
if(curNode->tile->letter == letter) {
// Letter found, remove node
tile = curNode->tile;
prevNode->next = curNode->next;
return tile;
}
prevNode = curNode;
curNode = curNode->next;
}
return NULL;
}
Tile* LinkedList::peek() {
if(head == nullptr) {
return NULL;
}
return this->head->tile;
}
Tile* LinkedList::get(Letter letter) {
Node* curNode = head;
Tile* tile = NULL;
// Traverse and search for letter
while(curNode != NULL) {
if(curNode->tile->letter == letter) {
// Letter found
tile = curNode->tile;
return tile;
}
curNode = curNode->next;
}
return NULL;
}