-
Notifications
You must be signed in to change notification settings - Fork 4
/
stack.h
72 lines (52 loc) · 1.28 KB
/
stack.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
#ifndef LITE__STACK_H
#define LITE__STACK_H
#include <lace/do_not_copy.h>
#include "link.h"
#include <cassert>
#include <cstddef>
namespace lite {
template <class X>
struct stack_link : private link<X> {
typedef stack_link type;
template <class T, typename stack_link<T>::type T::*L>
friend class stack;
bool bound() const { return link<X>::p; }
};
template <class T, typename stack_link<T>::type T::*L>
class stack : public lace::do_not_copy {
public:
stack() : head(const_cast<T*>(sentinel())) { }
~stack() { assert(empty()); }
bool empty() const { return head == sentinel(); }
stack & push(T* t) {
assert(!(t->*L).bound());
(t->*L).p = head;
head = t;
assert((t->*L).bound());
assert(!empty());
return *this;
}
T* peek() const {
assert(!empty());
return head;
}
T* pop() {
assert(!empty());
T* t = head;
assert((t->*L).bound());
head = (t->*L).p;
(t->*L).p = NULL;
assert(!(t->*L).bound());
return t;
}
T* iterator() const { return !empty() ? head : NULL; }
T* next(const T* t) const {
assert((t->*L).bound());
return (t->*L).guarded(sentinel());
}
private:
T * head;
const T* sentinel() const { return reinterpret_cast<const T*>(&head); }
};
} // namespace lite
#endif//LITE__STACK_H