-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.cpp
105 lines (85 loc) · 2.28 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
#include "LinkedList.hpp"
LinkedList *LinkedList::pHead = 0;
int LinkedList::size = 0;
LinkedList::LinkedList() {
this->pHead = nullptr;
this->size = 0;
}
LinkedList::LinkedList(int data) {
this->data = data;
}
LinkedList::LinkedList(const LinkedList& orig) {
}
LinkedList::~LinkedList() {
}
void LinkedList::add(int nData) {
LinkedList* pCurrentPos = LinkedList::pHead;
LinkedList* pNewData = new LinkedList(nData);
pNewData->pNext = 0;
if (pHead == 0) {
pHead = pNewData;
} else {
while (pCurrentPos->pNext) {
pCurrentPos = pCurrentPos->pNext;
}
pCurrentPos->pNext = pNewData;
}
LinkedList::size++;
}
void LinkedList::remove(int nId) {
LinkedList* pCurrentPos = pHead;
if (nId > size - 1) {
return;
}
if (nId == size - 1) {
if (size == 1) {
removeNode(pCurrentPos);
pHead = nullptr;
return;
}
for (int i = 0;; i++) {
if (i == nId - 1) {
LinkedList *pPrevPos = pCurrentPos;
pCurrentPos = pCurrentPos->pNext;
removeNode(pCurrentPos);
pPrevPos->pNext = 0;
return;
}
pCurrentPos = pCurrentPos->pNext;
}
}
if (nId == 0) {
pHead = pCurrentPos->pNext;
removeNode(pCurrentPos);
return;
}
for (int i = 0;; i++) {
if (i == nId - 1) {
LinkedList *pDeadNode = pCurrentPos;
pCurrentPos->pNext = pCurrentPos->pNext->pNext;
return;
}
pCurrentPos = pCurrentPos->pNext;
}
removeNode(pCurrentPos);
}
void LinkedList::removeNode(LinkedList *node) {
delete node;
LinkedList::size--;
}
void LinkedList::out() {
if (LinkedList::pHead == nullptr)
return;
LinkedList* pCurrentPos = LinkedList::pHead;
while (pCurrentPos->pNext) {
std::cout << pCurrentPos->data << " ";
pCurrentPos = pCurrentPos->pNext;
}
std::cout << pCurrentPos->data << std::endl;
}
void LinkedList::clear() {
if (pHead != nullptr)
for (int i = size; i != 0; i--) {
remove(0);
}
}