-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.h
117 lines (91 loc) · 3.08 KB
/
LinkedList.h
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
#pragma once
#include <iostream>
#include "LinkedListNode.h"
using namespace std;
template <class DataType>
class LinkedList {
public:
LinkedList() :
mpFirstNode(0),
mpLastNode(0) {}
~LinkedList() {
LinkedListNode<DataType>* deleteNode = mpFirstNode;
while (deleteNode != 0) {
LinkedListNode<DataType>* nextNode = deleteNode->next();
delete deleteNode;
deleteNode = nextNode;
}
}
const LinkedListNode<DataType>* const firstNode() const
{ return mpFirstNode; }
LinkedListNode<DataType>* firstNode() { return mpFirstNode; }
LinkedListNode<DataType>* insertAfter(LinkedListNode<DataType>* pAfterNode,
const DataType& data) {
if (pAfterNode == 0) {
// If we're inserting after NULL, interpret that as "insert at the
// begninning of the list"
LinkedListNode<DataType>* pInsertNode =
new LinkedListNode<DataType>(data, mpFirstNode);
if (mpFirstNode == 0) {
mpLastNode = pInsertNode;
}
mpFirstNode = pInsertNode;
return pInsertNode;
} else {
LinkedListNode<DataType>* pInsertNode =
new LinkedListNode<DataType>(data, pAfterNode->next());
pAfterNode->setNext(pInsertNode);
if (pInsertNode->next() == 0) {
mpLastNode = pInsertNode;
}
return pInsertNode;
}
}
LinkedListNode<DataType>* insertEnd(const DataType& data) {
return this->insertAfter(mpLastNode, data);
}
LinkedListNode<DataType>* insertBeginning(const DataType& data) {
return this->insertAfter(0, data);
}
void removeAfter(LinkedListNode<DataType>* pAfterNode) {
if (pAfterNode == 0) {
// If pAfterNode is 0, then delete the first item in the list
if (mpFirstNode != 0) {
LinkedListNode<DataType>* pDeleteNode = mpFirstNode;
mpFirstNode = mpFirstNode->next();
delete pDeleteNode;
if (mpFirstNode == 0) {
mpLastNode = 0;
}
}
} else {
LinkedListNode<DataType>* pNextNode = pAfterNode->next();
if (pNextNode != 0) {
if (pNextNode->next() == 0) {
mpLastNode = pAfterNode;
}
pAfterNode->setNext(pNextNode->next());
delete pNextNode;
}
}
}
void removeBeginning() {
this->removeAfter(0);
}
void print() {
if (mpFirstNode == 0) {
cout << "NULL";
} else {
cout << mpFirstNode->data();
LinkedListNode<DataType>* currentNode = mpFirstNode->next();
while (currentNode != 0) {
cout << " -> " << currentNode->data();
currentNode = currentNode->next();
}
}
cout << endl;
}
private:
LinkedListNode<DataType>* mpFirstNode;
LinkedListNode<DataType>* mpLastNode;
};