-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path3)Stack Array.cpp
105 lines (83 loc) · 1.69 KB
/
3)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
#include<iostream>
using namespace std;
class Stack{
private:
int capacity;
int* arr; // This is pointer to the first element of stack
int topindex;
public:
// Parametrised constructor
Stack(int maxsize){
capacity = maxsize;
// dynamically create a array of size = capacity
arr = new int[capacity];
topindex = -1;
}
bool isFull();
bool isempty();
void push(int);
void pop();
void display();
int getTop();
int size();
};
bool Stack :: isempty(){
return (topindex==-1);
}
bool Stack :: isFull(){
return (topindex==capacity-1);
}
void Stack :: push(int val){
if(!isFull()){
topindex+=1;
arr[topindex] = val;
}
else{
cout << "\nStack overflow\n";
}
}
void Stack :: pop(){
if(!isempty()){
topindex-=1;
}
else{
cout << "Stack empty or underflow\n";
}
}
int Stack :: getTop(){
if(!isempty()){
return arr[topindex];
}
else{
cout << "Stack is empty\n";
return -1;
}
}
int Stack :: size(){
return topindex+1;
}
void Stack :: display(){
if(!isempty()){
for(int i=topindex;i>=0;i--){
cout << arr[i] << endl;
}
}
else{
cout << "Stack is empty\n";
}
}
int main(){
Stack s(5);
for(int i=1;i<=5;i++){
s.push(i);
}
s.display();
s.pop();
s.pop();
s.pop();
cout << "After popping top three elements: \n";
s.display();
cout << "Current size of stack is : " << s.size()<<endl;
cout << "Top element is : " << s.getTop()<<endl;
return 0;
}