-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.cpp
More file actions
156 lines (117 loc) · 2.5 KB
/
LinkedList.cpp
File metadata and controls
156 lines (117 loc) · 2.5 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
/* Leonardo Pinheiro de Souza - 32127391
Matheus Farias de Oliveira Matsumoto - 32138271
Código em Inglês
Comentários em Portugês-BR
*/
#include "LinkedListSimple.h"
#include<iostream>
// Funções do Node
Node::Node()
:data(0), next(nullptr) {}
Node::~Node() {}
// Funções da LinkedList
LinkedList::LinkedList()
: count(0), head(nullptr), tail(nullptr) {}
LinkedList::~LinkedList() {}
void LinkedList::Insert(int elem) {
Node* node = new Node();
node->data = elem;
node->next = head;
if (isEmpty() == true)
tail = node;
head = node;
count++;
}
void LinkedList::Append(int elem) {
Node* node = new Node();
node->data = elem;
node->next = nullptr;
if (isEmpty() == true)
head = node;
else
tail->next = node;
tail = node;
count++;
}
Node* LinkedList::RemoveHead() {
if (isEmpty() == true)
return nullptr;
Node* toRemove = head;
if (head == tail)
head, tail = nullptr;
else
head = head->next;
count--;
toRemove->next = nullptr;
return toRemove;
}
Node* LinkedList::RemoveTail() {
if (head == tail)
return RemoveHead();
Node* toRemove = head;
Node* previous = nullptr;
while (toRemove != tail)
{
previous = toRemove;
toRemove = toRemove->next;
}
previous->next = nullptr;
tail = previous;
count--;
toRemove->next = nullptr;
return toRemove;
}
Node* LinkedList::RemoveNode(int elem) {
Node* toRemove = head;
Node* previous = nullptr;
while (toRemove != nullptr && toRemove->data != elem) {
previous = toRemove;
toRemove = toRemove->next;
}
if (toRemove == nullptr)
return nullptr;
else if (toRemove == head)
return RemoveHead();
else if (toRemove == tail)
return RemoveTail();
else {
previous->next = toRemove->next;
count--;
toRemove->next = nullptr;
return toRemove;
}
}
Node* LinkedList::GetNode(int elem) {
Node* node = head;
while (node != nullptr) {
if (node->data == elem)
return node;
node = node->next;
}
return nullptr;
}
Node* LinkedList::GetHead() {
return head;
}
Node* LinkedList::GetTail() {
return tail;
}
int LinkedList::Count() {
return count;
}
bool LinkedList::isEmpty() {
if (head == nullptr)
return true;
else
false;
}
void LinkedList::Clear() {
Node* next = nullptr;
while (head != nullptr) {
next = head->next;
delete head; // Parte importante para liberar espaço na memória
head = next;
}
head, tail = nullptr;
count = 0;
}