Skip to content

Commit 2345d20

Browse files
committed
two stacks in array
1 parent 969e0c5 commit 2345d20

File tree

1 file changed

+112
-0
lines changed

1 file changed

+112
-0
lines changed
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
2+
/*
3+
Problem link- https://practice.geeksforgeeks.org/problems/implement-two-stacks-in-an-array/1
4+
*/
5+
6+
#include<bits/stdc++.h>
7+
using namespace std;
8+
class twoStacks
9+
{
10+
int *arr;
11+
int size;
12+
int top1, top2;
13+
public:
14+
twoStacks(int n=100){size = n; arr = new int[n]; top1 = -1; top2 = size;}
15+
16+
void push1(int x);
17+
void push2(int x);
18+
int pop1();
19+
int pop2();
20+
};
21+
int main()
22+
{
23+
int T;
24+
cin>>T;
25+
while(T--)
26+
{
27+
twoStacks *sq = new twoStacks();
28+
int Q;
29+
cin>>Q;
30+
while(Q--){
31+
int stack_no;
32+
cin>>stack_no;
33+
int QueryType=0;
34+
cin>>QueryType;
35+
36+
if(QueryType==1)
37+
{
38+
int a;
39+
cin>>a;
40+
if(stack_no ==1)
41+
sq->push1(a);
42+
else if(stack_no==2)
43+
sq->push2(a);
44+
}else if(QueryType==2){
45+
if(stack_no==1)
46+
cout<<sq->pop1()<<" ";
47+
else if(stack_no==2)
48+
cout<<sq->pop2()<<" ";
49+
}
50+
}
51+
cout<<endl;
52+
}
53+
}
54+
55+
/*This is a function problem.You only need to complete the function given below*/
56+
/*The structure of the class is
57+
class twoStacks
58+
{
59+
int *arr;
60+
int size;
61+
int top1, top2;
62+
public:
63+
twoStacks(int n=100){size = n; arr = new int[n]; top1 = -1; top2 = size;}
64+
65+
void push1(int x);
66+
void push2(int x);
67+
int pop1();
68+
int pop2();
69+
};
70+
*/
71+
/* The method push to push element into the stack 2 */
72+
void twoStacks :: push1(int x)
73+
{
74+
if(top1<top2-1) {
75+
arr[++top1]=x;
76+
}
77+
else cout<<"stack overflow";
78+
}
79+
80+
/* The method push to push element into the stack 2*/
81+
void twoStacks ::push2(int x)
82+
{
83+
if(top1<top2-1) {
84+
arr[--top2]=x;
85+
}
86+
else cout<<"stack overflow";
87+
}
88+
89+
/* The method pop to pop element from the stack 1 */
90+
//Return the popped element
91+
int twoStacks ::pop1()
92+
{
93+
if(top1>=0) {
94+
top1--;
95+
return arr[top1+1];
96+
}
97+
else {
98+
return -1;
99+
}
100+
}
101+
/* The method pop to pop element from the stack 2 */
102+
//Return the popped element
103+
int twoStacks :: pop2()
104+
{
105+
if(top2<size) {
106+
top2++;
107+
return arr[top2-1];
108+
}
109+
else {
110+
return -1;
111+
}
112+
}

0 commit comments

Comments
 (0)