-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.h
88 lines (76 loc) · 1.39 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Stack.h
#include <cassert>
#include <cstddef>
#include <stdexcept>
#include <string>
#include <new>
using std::logic_error;
using std::string;
using std::bad_alloc;
// MS std namespace work-around
#ifndef _MSC_VER
using std::size_t;
#endif
class StackError : public logic_error {
public:
StackError(const string& s)
: logic_error(s)
{}
};
template<typename T>
class Stack
{
public:
Stack(size_t) throw(StackError, bad_alloc);
~Stack();
void push(const T&) throw(StackError);
T pop() throw(StackError);
T top() const throw(StackError);
size_t size() const;
private:
T* data;
size_t max;
size_t ptr;
};
template<typename T>
inline Stack<T>::~Stack()
{
delete [] data;
max = ptr = 0;
}
template<typename T>
inline size_t Stack<T>::size() const
{
return ptr;
}
template<typename T>
Stack<T>::Stack(size_t siz) throw(StackError, bad_alloc)
{
if (siz == 0)
throw StackError("bad size in Stack(size_t)");
data = new T[siz];
max = siz;
ptr = 0;
}
template<typename T>
void Stack<T>::push(const T& x) throw(StackError)
{
if (ptr == max)
throw StackError("stack overflow");
assert(ptr < max);
data[ptr++] = x;
}
template<typename T>
T Stack<T>::pop() throw(StackError)
{
if (ptr == 0)
throw StackError("stack underflow");
return data[--ptr];
}
template<typename T>
T Stack<T>::top() const throw(StackError)
{
if (ptr == 0)
throw StackError("stack underflow");
return data[ptr - 1];
}