-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStacksArray.cpp
More file actions
148 lines (114 loc) · 2.36 KB
/
Copy pathStacksArray.cpp
File metadata and controls
148 lines (114 loc) · 2.36 KB
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/* Name : Annie Bhalla
Roll No. : 19HCS4009
Course : BSC (H) Computer Science
Semester : 3
Subject : Data Structures
Title : Implementation of Stacks ( Array )
*/
#include<iostream>
#include<exception>
using namespace std;
//class StackEmpty : public RuntimeException
//{
//
// public:
// StackEmpty(const string& err)
// {
// RuntimeException(err);
// }
//};
template <typename E>
class Stack
{
private:
E* arr;
int capacity;
int t;
enum DEFCAPACITY {cap = 10};
public:
Stack(); // 1
Stack(int cap); // 2
int size() const; // 3
bool empty() const; // 4
const E& top()const ;//throw(EmptyStack); // 5
void push(const E& elem); // 6
void pop() ;// throw (StackEmpty); // 7
void display(); // 8
};
// (1) Default Constructor
template <typename E>
Stack<E>::Stack()
{
capacity= cap;
arr = new E[cap];
t=-1;
}
// (2) para constructor
template <typename E>
Stack<E>::Stack(int cap) : capacity(cap),arr(new E[cap]), t(-1){}
// (3) Return size
template <typename E>
int Stack<E>::size() const
{
return (t+1);
}
// (4) To check if stack is empty or not
template <typename E>
bool Stack<E>::empty() const
{
return (t<0);
}
// (5) To return element at top
template <typename E>
const E& Stack<E>::top() const
{
if(empty()) " Function top() : STACK UNDERFLOW ";
return (arr[t]);
}
// (6) To push an element to top of stack
template <typename E>
void Stack<E>::push(const E& elem)
{
if(t==capacity) throw " Function push() : STACK OVERFLOW ";
arr[++t]=elem;
}
// (7) To pop an element out of stack
template <typename E>
void Stack<E>::pop()
{
if(empty()) throw " Function pop() : STACK UNDERFLOW " ;
cout<<"\n Pop Element : "<<arr[t]<<endl;
t--;
}
// (8) To display elements in stack
template <typename E>
void Stack<E>::display()
{
if(empty()) throw " Function display() : STACK UNDERFLOW ";
for(int i=t;i>=0;i--)
{
cout<<arr[i]<<" -> ";
}
cout<<endl;
}
// Driver Code
int main()
{
try
{
Stack<int> S1(4);
S1.push(2);
S1.push(4);
S1.push(6);
S1.display();
cout<<S1.top()<<endl;
S1.pop();
cout<<S1.top()<<endl;
S1.display();
}
catch(const char* str)
{
cout<<"\n Exception Found From : "<<str;
}
return 0;
}