-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.cpp
98 lines (86 loc) · 1.33 KB
/
Stack.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
// $Id: Stack.cpp 827 2011-02-07 14:20:53Z hillj $
// Honor Pledge:
//
// I pledge that I have neither given nor received any help
// on this assignment.
//
// Stack
//
#include "Stack.h"
template <typename T>
Stack <T>::Stack (void)
: arr (Array<T>()),
head (-1)
{
}
//
// Stack
//
template <typename T>
Stack <T>::Stack (const Stack & stack)
: arr (Array<T>(stack.arr)),
head (stack.head)
{
}
//
// ~Stack
//
template <typename T>
Stack <T>::~Stack (void)
{
}
//
// push
//
template <typename T>
void Stack <T>::push (T element)
{
// if there is still room in the current array to expand
if (head + 1 < (int)arr.size()){
head++;
arr.set(head, element);
// if we can expand the array without allocating new memory
}else if (arr.size() < arr.max_size()) {
arr.resize(arr.size()+1);
head++;
arr.set(head, element);
} else{
arr.resize(arr.size()*2+1);
head++;
arr.set(head, element);
}
}
//
// pop
//
template <typename T>
void Stack <T>::pop (void)
{
if(head != -1){
head--;
}else {
throw empty_exception();
}
}
//
// operator =
//
template <typename T>
const Stack <T> & Stack <T>::operator = (const Stack & rhs)
{
head = rhs.head;
arr = rhs.arr;
}
//
// clear
//
template <typename T>
void Stack <T>::clear (void)
{
head = -1;
}
template <typename T>
void Stack <T>::reverse() {
arr.resize(head+1);
arr.reverse();
}