-
Notifications
You must be signed in to change notification settings - Fork 1
/
stack.cpp
executable file
·111 lines (104 loc) · 1.85 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
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <iostream>
using namespace std;
class StackoverflowException : public exception
{
virtual const char *what() const throw()
{
return "\nStack overflow\n";
}
};
class StackunderflowException : public exception
{
virtual const char *what() const throw()
{
return "\nStack underflow\n";
}
};
//generic implementation of standard Stack data structure using templates
template <class T>
class Stack
{
private:
static const int MAX_SIZE = 100;
T data[MAX_SIZE];
int top;
public:
Stack()
{
top = -1;
}
void Push(const T element)
{
if (top >= MAX_SIZE)
{
StackoverflowException e;
throw e;
}
else
{
data[++top] = element;
}
}
T Pop()
{
if (top <= -1)
{
StackunderflowException e;
throw e;
}
else
{
return data[top--];
}
}
T Top()
{
if (top <= -1)
{
StackunderflowException e;
throw e;
}
else
{
return data[top];
}
}
int Size()
{
if (top <= -1)
{
StackunderflowException e;
throw e;
}
else
{
return top + 1;
}
}
bool isEmpty()
{
return (top <= -1) ? true : false;
}
};
int main()
{
Stack<int> s;
if (s.isEmpty())
{
cout << "Stack is empty\n";
}
// Push elements
s.Push(100);
s.Push(200);
// Size of stack
cout << "Size of stack = " << s.Size() << endl;
// Top element
cout << s.Top() << endl;
// Pop element
cout << s.Pop() << endl;
// Pop element
cout << s.Pop() << endl;
// Pop element
cout << s.Pop() << endl;
return 0;
}