-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.h
68 lines (56 loc) · 1.33 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
#pragma once
#include <cstdlib>
template<class T> class Stack
{
// LIFO objects
public:
Stack(int MaxStackSize = 10) // constructor
{
//Pre: none'
//Post: Array of size MaxStackSaize to implement stack
MaxTop = MaxStackSize - 1;
stack = new T[MaxStackSize];
top = -1;
}
~Stack() { delete[] stack; } // destructor
bool IsEmpty() const { return top == -1; }
bool IsFull() const { return top == MaxTop; }
T& Top() const
{
//Pre: stack is not empty
// Post: Returns top element.
if (IsEmpty())
throw logic_error("Top fails: Stack is empty");// Top fails
return stack[top];
}
void push(const T& x)
{
//Pre: Stack is not full
//Post: Push x to stack.
// Stack has one more element
if (IsFull()) throw logic_error("Push fails: full stack"); // Push fails
stack[++top] = x;
}
void pop()
{
//Pre: Stack is not Empty
//Post: Stack has one less element
if (IsEmpty()) {
throw logic_error("Pop fails: Stack is empty");
}; // Pop fails
top--;
}
int search(const T& x)
{
for (int i = 0; i <= top; i++)
{
if (x == stack[i])
return i;
}
return -1;
}
private:
int top; // current top of stack
int MaxTop; // max value for top
T *stack; // element array
};