-
Notifications
You must be signed in to change notification settings - Fork 1
/
doublelinkedlistarray.h
executable file
·169 lines (133 loc) · 3.17 KB
/
doublelinkedlistarray.h
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
/*************************************
*
* Author: Tian-Li Yu
* Email: tianliyu@ntu.edu.tw
* Date: 2014 Dec
*
*
* Use array to simulate a double linked list
* Insert: O(1)
* Delete: O(1)
* Has: O(1)
* Space Complexity: O(ell)
**************************************/
#ifndef _DLLA_
#define _DLLA_
#include <cstdio>
#include <vector>
using namespace std;
class DLLA {
public:
DLLA(int _length) : data(_length,false), pre(_length), next(_length) {
tableSize = _length;
elementSize = 0;
head = -1;
}
void operator= (const DLLA& h) {
head = h.head;
elementSize = h.elementSize;
data = h.data;
pre = h.pre;
next = h.next;
}
bool find(int key) const {
return data[key];
}
void insert(int key) {
++elementSize;
if (head == -1) {
head = key;
data[key] = true;
pre[key] = key;
next[key] = key;
} else {
data[key] = true;
int temp = pre[head];
pre[head] = key;
pre[key] = temp;
next[key] = head;
next[pre[key]] = key;
}
}
void erase(int key) {
if (elementSize == 0) return;
--elementSize;
if (elementSize == 0) {
data[key] = false;
head = -1;
} else {
data[key] = false;
next[pre[key]] = next[key];
pre[next[key]] = pre[key];
if (head == key)
head = pre[key];
}
}
void eraseAll() {
head = -1;
for (int i=0; i<tableSize; i++)
data[i] = false;
}
int getElementSize() const {
return elementSize;
}
bool isEmpty() const {
return (elementSize==0);
}
// Iterator
class iterator {
protected:
DLLA* pArray;
int index;
int real_end;
bool flag;
public:
iterator(DLLA* p = NULL, int nIndex = -1) {
pArray = p;
index = nIndex;
flag = false;
if (pArray->head == -1)
real_end = -1;
else
real_end = pArray->pre[pArray->head];
}
void operator++() { // Prefix
if (flag)
index = -1;
else {
index = pArray->next[index];
if (index == real_end)
flag = true;
else if (index == pArray->head) index = -1;
}
}
void operator++(int) { // Postfix
operator++();
}
bool operator==(const iterator& iter) const {
return (index == iter.index);
}
bool operator!=(const iterator& iter) const {
return !(operator==(iter));
}
int& operator*() {
return index;
}
};
iterator begin() {
iterator iter(this, head);
return iter;
}
iterator end() {
iterator iter(this, -1);
return iter;
}
protected:
int tableSize;
int elementSize;
vector<bool> data;
vector<int> pre;
vector<int> next;
int head;
};
#endif