-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSta.cpp
109 lines (90 loc) · 1.69 KB
/
Sta.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
constexpr unsigned max(unsigned a, unsigned b)
{ return a > b ? a : b; }
template<typename T, typename Alloc = std::allocator<T>, int init_size = max(512 / sizeof(T), 8u)>
class Sta
{
public:
typedef T value_type;
typedef T& reference;
typedef T* pointer;
typedef const T& const_reference;
typedef size_t size_type;
Sta():
p(nullptr),
garbage(nullptr)
{}
~Sta()
{
if(garbage) {
alloc.deallocate(garbage->begin, garbage->end - garbage->begin);
delete garbage;
}
if(p) {
Node *temp;
for(T *i = p->begin; i <= it; i++)
alloc.destroy(i);
alloc.deallocate(p->begin, p->end - p->begin);
temp = p;
p = p->pre;
delete temp;
while(p) {
for(T *i = p->begin; i != p->end; i++)
alloc.destroy(i);
alloc.deallocate(p->begin, p->end - p->begin);
temp = p;
p = p->pre;
delete temp;
}
}
}
void push(T x)
{
++it;
if(! p || it == p->end) {
if(garbage) {
it = garbage->begin;
p = garbage;
garbage = nullptr;
}
else {
size_t x = p ? (p->end - p->begin) * 2 : init_size;
it = alloc.allocate(x);
p = new Node{ p, it, it + x };
}
}
alloc.construct(it, x);
}
void pop()
{
alloc.destroy(it);
if(it == p->begin) {
if(garbage) {
alloc.deallocate(garbage->begin, garbage->end - garbage->begin);
delete garbage;
}
garbage = p;
p = p->pre;
if(p)
it = p->end - 1;
}
else
it--;
}
T& top()
{ return *it; }
bool empty()
{ return ! p; }
size_t size()
{ return p ? p->end - p->begin + it - p->begin - init_size + 1 : 0; }
private:
struct Node
{
Node *pre;
T *begin;
T *end;
};
T *it;
Node *p;
Node *garbage;
Alloc alloc;
};