-
Notifications
You must be signed in to change notification settings - Fork 18
/
dynamic_stacks_using_array_and_template.cpp
121 lines (96 loc) · 2.23 KB
/
dynamic_stacks_using_array_and_template.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
#include <iostream>
using namespace std;
template<typename T> //template
class StackUsingArray{
T *data;
int nextIndex;
int capacity;
public:
StackUsingArray(){
data= new T[4];
nextIndex=0;
capacity=4;
}
int size(){
return nextIndex;
}
bool checkEmpty(){
return nextIndex==0;
}
void push(T element){
if(nextIndex==capacity){
T *newdata=new T[capacity*2]; //dynamic_stack
for(int i=0;i<capacity;i++){
newdata[i]=data[i];
}
capacity*=2;
delete []data;
data=newdata;
}
data[nextIndex]=element;
nextIndex++;
}
int pop(){
if(checkEmpty()){
cout<<"stack is empty"<<endl;
return 0;
}
nextIndex--;
return data[nextIndex];
}
int top(){
return data[nextIndex-1];
}
void display(){
for(int i=0;i<nextIndex;i++){
cout<<data[i]<<endl;
}
}
};
int main(){
StackUsingArray<int> s;
int ch;
while(ch!=7)
{
cout<<"\n1. Push\n";
cout<<"2. Pop\n";
cout<<"3. top\n";
cout<<"4. size\n";
cout<<"5. check\n";
cout<<"6. display\n";
cout<<"\nEnter your Choice :: ";
cin>>ch;
switch(ch)
{
case 1:
int x;
cout<<"enter the element"<<endl;
cin>>x;
s.push(x);
break;
case 2:
s.pop();
break;
case 3:
cout<<s.top()<<endl;
break;
case 4:
s.size();
break;
case 5:
s.checkEmpty();
break;
case 6:
s.display();
break;
case 7:
ch=7;
cout<<"\nPress any key .. ";
break;
default:
cout<<"\nWrong Choice!! \n";
break;
}
}
return 0;
}