-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.cpp
191 lines (143 loc) · 3.1 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
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
template <typename T>
class List
{
struct Node
{
public:
T m_data;
Node *m_prev;
Node *m_next;
Node(const T &data)
{
m_prev = m_next = NULL;
m_data = data;
}
};
public:
Node *m_head;
Node *m_tail;
size_t m_size;
List()
{
m_size = 0;
m_head = m_tail = NULL;
}
List(const List &source)
{
m_head = m_tail = NULL;
m_size = source.m_size;
Node *i = source.m_head;
while (i != NULL)
{
push_back(i->m_data);
i = i->m_next;
}
}
~List()
{
clear();
}
size_t size()
{
return m_size;
}
bool is_empty()
{
return m_size == 0;
}
void clear()
{
while (!is_empty())
pop_back();
}
void push_back(const T &data)
{
Node *add_elem = new Node (data);
if (m_size == 0)
{
m_head = add_elem;
}
else
{
m_tail->m_next = add_elem;
add_elem->m_prev = m_tail;
}
m_tail = add_elem;
++m_size;
}
T pop_back()
{
T ret_item = m_tail->m_data;
Node *new_tail = m_head == m_tail ? NULL : m_tail->m_prev;
delete m_tail;
if (m_head == m_tail)
m_head = NULL;
m_tail = new_tail;
--m_size;
return ret_item;
}
void push_front(const T &data)
{
Node *add_item = new Node (data);
if (m_size == 0)
{
m_tail = add_item;
}
else
{
m_head->m_prev = add_item;
add_item->m_next = m_head;
}
m_head = add_item;
++m_size;
}
T pop_front()
{
T ret_item = m_head->m_data;
Node *new_head = m_head == m_tail ? NULL : m_head->m_next;
delete m_head;
if (m_head == m_tail)
m_tail = 0;
m_head = new_head;
--m_size;
return ret_item;
}
int count(const T &data)
{
Node *temp;
int count = 0;
for (temp = m_head; temp; temp = temp->m_next)
if (temp->m_data == data)
count++;
return count;
}
bool erase(const T &data)
{
Node *temp;
for (temp = m_head; temp; temp = temp->m_next)
if (temp->m_data == data)
{
if (temp == m_head)
m_head = temp->m_next;
if (temp == m_tail)
m_tail = temp->m_prev;
Node *n_prev = temp->m_prev;
Node *n_next = temp->m_next;
if (n_prev)
n_prev->m_next = n_next;
if (n_next)
n_next->m_prev = n_prev;
delete temp;
m_size--;
return true;
}
return false;
}
int all_erase(const T &data)
{
int count = 0;
while (erase(data))
count++;
return count;
}
};