-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_Array.cpp
122 lines (98 loc) · 1.9 KB
/
stack_Array.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
112
113
114
115
116
117
118
119
120
121
122
#include <iostream>
#include <cstdlib>
using namespace std;
// define default capacity of the stack
#define SIZE 10
// Class for stack
class stack
{
int *arr;
int top;
int capacity;
public:
stack(int size = SIZE); // constructor
~stack(); // destructor
void push(int);
int pop();
int peek();
int size();
bool isEmpty();
bool isFull();
};
// Constructor to initialize stack
stack::stack(int size)
{
arr = new int[size];
capacity = size;
top = -1;
}
// Destructor to free memory allocated to the stack
stack::~stack()
{
delete arr;
}
// Utility function to add an element x in the stack
void stack::push(int x)
{
if (isFull())
{
cout << "OverFlow\nProgram Terminated\n";
exit(EXIT_FAILURE);
}
cout << "Inserting " << x << endl;
arr[++top] = x;
}
// Utility function to pop top element from the stack
int stack::pop()
{
// check for stack underflow
if (isEmpty())
{
cout << "UnderFlow\nProgram Terminated\n";
exit(EXIT_FAILURE);
}
cout << "Removing " << peek() << endl;
// decrease stack size by 1 and (optionally) return the popped element
return arr[top--];
}
// Utility function to return top element in a stack
int stack::peek()
{
if (!isEmpty())
return arr[top];
else
exit(EXIT_FAILURE);
}
// Utility function to return the size of the stack
int stack::size()
{
return top + 1;
}
// Utility function to check if the stack is empty or not
bool stack::isEmpty()
{
return top == -1; // or return size() == 0;
}
// Utility function to check if the stack is full or not
bool stack::isFull()
{
return top == capacity - 1; // or return size() == capacity;
}
// main function
int main()
{
stack pt(3);
pt.push(1);
pt.push(2);
pt.pop();
pt.pop();
pt.push(3);
cout << "Top element is: " << pt.peek() << endl;
cout << "Stack size is " << pt.size() << endl;
pt.pop();
if (pt.isEmpty())
cout << "Stack Is Empty\n";
else
cout << "Stack Is Not Empty\n";
return 0;
}