-
Notifications
You must be signed in to change notification settings - Fork 20
/
List.cpp
109 lines (86 loc) · 1.81 KB
/
List.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
#include <iostream>
template < typename T >
class Node
{
public:
T data;
Node* next;
Node (T data) { this->data = data; }
Node(){}
};
template < typename T >
class List
{
public:
int count;
Node<T>* head = new Node<T>;
List ();
void add (T data);
void remove (int index);
int size () { return this->count; }
void print ();
};
template <typename T>
List<T>::List ()
{
this->count = 0;
this->head->next = nullptr;
this->head->next = nullptr;
}
template < typename T >
void List<T>::add (T data)
{
Node<T>* newNode = new Node<T>(data);
newNode->next = nullptr;
if (head->next == nullptr) { head->next = newNode; }
else {
Node<T>* temp = head;
while (temp->next != nullptr)
temp = temp->next;
temp->next = newNode;
}
++List::count;
}
template <typename T>
void List<T>::remove (int index)
{
Node<T>* temp = head;
Node<T>* target = head;
if(count < index) { std::cout << "out of index!" << std::endl; return; }
for (int i = 0; i < index; ++i) {
temp = temp->next;
target = target->next;
}
target = target->next;
temp->next = target->next;
target->next = nullptr;
delete target;
--List::count;
}
template <typename T>
void List<T>::print ()
{
Node<T>* iterator;
iterator = head;
while(iterator->next != nullptr) {
iterator = iterator->next;
std::cout << iterator->data << " ";
}
std::cout << std::endl;
}
int main ()
{
// These codes are test
List<char> test;
test.add ('A');
test.print ();
test.add ('B');
test.print ();
test.add ('C');
test.print ();
test.remove(5);
test.print();
test.remove(1);
test.print();
return 0;
}