This repository has been archived by the owner on Nov 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 582
/
2StackInAnArray.cpp
182 lines (166 loc) · 3.21 KB
/
2StackInAnArray.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
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#include <iostream>
#include <stdlib.h>
using namespace std;
class twoStacks
{
int *arr;
int size;
int top1, top2;
public:
twoStacks(int n)
{
size = n;
arr = new int[n];
top1 = -1;
top2 = size;
}
void push1(int x)
{
if (top1 < top2 - 1)
{
top1++;
arr[top1] = x;
}
else
{
cout << "Stack Overflow";
exit(1);
}
}
void push2(int x)
{
if (top1 < top2 - 1)
{
top2--;
arr[top2] = x;
}
else
{
cout << "Stack Overflow";
exit(1);
}
}
int pop1()
{
if (top1 >= 0)
{
int x = arr[top1];
top1--;
return x;
}
else
{
cout << "Stack UnderFlow";
return -1;
}
}
int pop2()
{
if (top2 < size)
{
int x = arr[top2];
top2++;
return x;
}
else
{
cout <<endl<< "Stack UnderFlow";
return -1;
}
}
void display()
{
cout << "Stack 1 ";
if (top1 >= 0)
{
for (int i = top1; i >= 0; i--)
cout << arr[i] << " ";
}
else
cout << "Stack is empty";
cout << endl;
cout << "Stack 2: " ;
if (top2 != size)
{
for (int i = top2; i < size; i++)
{
cout << arr[i] << " ";
}
}
else
{
cout << "Stack is empty";
}
cout << endl;
}
};
int main()
{
int n;
cout << "Enter the size of the stack ";
cin >> n;
twoStacks ts(n);
int ch, val;
do
{
cout << "1) Push in stack 1" << endl;
cout << "2) Push in stack 2" << endl;
cout << "3) Pop from stack 1" << endl;
cout << "4) Pop from stack 2" << endl;
cout << "5) Display Stack" << endl;
cout << "6) Exit" << endl;
cout << "Enter choice: " << endl;
cin >> ch;
switch (ch)
{
case 1:
{
cout << "Enter value to be pushed in stack 1:" << endl;
cin >> val;
ts.push1(val);
break;
}
case 2:
{
cout << "Enter value to be pushed in stack 2: " << endl;
cin >> val;
ts.push2(val);
break;
}
case 3:
{
int x = ts.pop1();
if (x != -1)
{
cout << "Popped Value from stack 1 is " << x << endl;
break;
}
break;
}
case 4:
{
int x = ts.pop2();
if (x != -1)
{
cout << "Popped Value from stack 2 is " << x << endl;
break;
}
break;
}
case 5:
{
ts.display();
break;
}
case 6:
{
cout << "Exit" << endl;
break;
}
default:
{
cout << "Invalid Choice" << endl;
}
}
} while (ch != 6);
}