-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlist_array.cpp
More file actions
63 lines (57 loc) · 1.23 KB
/
Copy pathlist_array.cpp
File metadata and controls
63 lines (57 loc) · 1.23 KB
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
#include "list_array.h"
#include <iostream>
#include <cstdlib>
using namespace std;
template <class T>
void copy(T* src, T* dest, int size) {
for (int i = 0; i < size; i++) {
dest[i] = src[i];
}
}
template <class T>
bool ListArray<T>::insert(int pos, const T & item) {
if (pos < 0 || pos > length) return false;
if (length == cur_size) {
T* tmp = (T*) malloc(cur_size * 2 * sizeof(T));
copy(list, tmp, length);
free(list);
list = tmp;
cur_size *= 2;
}
for (int j = length; j > pos; j--) {
list[j] = list[j-1];
}
list[pos] = item;
length ++;
return true;
}
template <class T>
bool ListArray<T>::remove(int pos) {
if (pos < 0 || pos >= length) return false;
for (int i = pos; i < length; i++) {
list[i] = list[i+1];
}
length --;
if (length <= cur_size / 2 && length > MIN_LENGTH) {
T* tmp = (T*) malloc(cur_size / 2 * sizeof(T));
copy(list, tmp, length);
free(list);
list = tmp;
cur_size /= 2;
}
return true;
}
template <class T>
bool ListArray<T>::set(int pos, const T & item) {
if (pos < 0 || pos >= length) return false;
list[pos] = item;
return true;
}
template <class T>
T & ListArray<T>::get(int pos) const {
if (pos < 0 || pos >= length) {
cout << "Invalid range!";
exit(1);
}
return list[pos];
}