-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.cpp
101 lines (100 loc) · 2.35 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
#include "Node.cpp"
#include <iostream>
using namespace std;
class OneWayLinkedList
{
public:
void AddNode(OneWayNode *node)
{
if (node)
{
if (start == 0)
start = node;
else
{
OneWayNode *active = start;
while (active->next != nullptr)
{
active = active->next;
}
active->next = node;
return;
}
}
}
void RemoveNode(int index)
{
int length = GetLength();
if (index < length && length != -1)
{
OneWayNode *wanted = GetNode(index);
OneWayNode *before = 0;
OneWayNode *scan = start;
if (scan->next != 0)
while (scan->next != wanted)
{
scan = scan->next;
}
before = scan;
before->next = wanted->next;
}
}
OneWayNode *GetNode(int index)
{
int length = GetLength();
if (index < length && length != -1)
{
OneWayNode *active = start;
while (index > 0)
{
active = active->next;
index--;
}
return active;
}
else
return 0;
}
OneWayLinkedList() {}
~OneWayLinkedList() {}
OneWayNode *start=nullptr;
int GetLength()
{
int length = 0;
if (start)
{
OneWayNode *active = start;
length++;
while (active->next != 0)
{
active = active->next;
length++;
}
}
return length;
}
};
int main()
{
OneWayLinkedList *list = new OneWayLinkedList();
list->AddNode(new OneWayNode(4));
list->AddNode(new OneWayNode(44));
list->AddNode(new OneWayNode(25));
list->AddNode(new OneWayNode(94));
list->AddNode(new OneWayNode(21));
list->AddNode(new OneWayNode(46));
int length = list->GetLength();
for(int i = 0; i < length ; i++)
{
cout << list->GetNode(i)->data << endl;
}
cout << endl;
list->RemoveNode(1);
list->RemoveNode(3);
length = list->GetLength();
for(int i = 0; i < length ; i++)
{
cout << list->GetNode(i)->data << endl;
}
return 0;
}