-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplement two stacks in an array.cpp
More file actions
118 lines (101 loc) · 2.27 KB
/
Copy pathImplement two stacks in an array.cpp
File metadata and controls
118 lines (101 loc) · 2.27 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
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class twoStacks {
int* arr;
int size;
int top1, top2;
public:
// Constructor
twoStacks()
{
size = 100000;
int n = size;
arr = new int[n];
top1 = n / 2 + 1;
top2 = n / 2;
}
// Method to push an element x to stack1
void push1(int x)
{
// There is at least one empty
// space for new element
if (top1 > 0) {
top1--;
arr[top1] = x;
}
else {
cout << "Stack Overflow"
<< " By element : " << x << endl;
return;
}
}
// Method to push an element
// x to stack2
void push2(int x)
{
// There is at least one empty
// space for new element
if (top2 < size - 1) {
top2++;
arr[top2] = x;
}
}
// Method to pop an element from first stack
int pop1()
{
if (top1 <= size / 2) {
int x = arr[top1];
top1++;
return x;
}
else {
return -1;
}
}
// Method to pop an element
// from second stack
int pop2()
{
if (top2 >= size / 2 + 1) {
int x = arr[top2];
top2--;
return x;
}
else {
return -1;
}
}
};
//{ Driver Code Starts.
int main() {
int T;
cin >> T;
while (T--) {
twoStacks *sq = new twoStacks();
int Q;
cin >> Q;
while (Q--) {
int stack_no;
cin >> stack_no;
int QueryType = 0;
cin >> QueryType;
if (QueryType == 1) {
int a;
cin >> a;
if (stack_no == 1)
sq->push1(a);
else if (stack_no == 2)
sq->push2(a);
} else if (QueryType == 2) {
if (stack_no == 1)
cout << sq->pop1() << " ";
else if (stack_no == 2)
cout << sq->pop2() << " ";
}
}
cout << endl;
}
}
// } Driver Code Ends