-
Notifications
You must be signed in to change notification settings - Fork 0
/
Implement two stacks in an array.java
96 lines (85 loc) · 1.57 KB
/
Implement two stacks in an array.java
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
//{ Driver Code Starts
import java.util.*;
class TwoStack
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T>0)
{
twoStacks g = new twoStacks();
int Q = sc.nextInt();
while(Q>0)
{
int stack_no = sc.nextInt();
int QueryType = sc.nextInt();
if(QueryType == 1)
{
int a = sc.nextInt();
if(stack_no == 1)
g.push1(a);
else if(stack_no ==2)
g.push2(a);
}else if(QueryType == 2)
{
if(stack_no==1)
System.out.print(g.pop1()+" ");
else if(stack_no==2)
System.out.print(g.pop2()+" ");
}
Q--;
}
System.out.println();
T--;
}
}
}
// } Driver Code Ends
class twoStacks
{
int arr[];
int size;
int top1, top2;
twoStacks()
{
size = 100;
arr = new int[100];
top1 = -1;
top2 = size;
}
//Function to push an integer into the stack1.
void push1(int x)
{
top1++;
arr[top1]=x;
}
//Function to push an integer into the stack2.
void push2(int x)
{
top2--;
arr[top2]=x;
}
//Function to remove an element from top of the stack1.
int pop1()
{
if(top1==-1)
return -1;
else
{
top1--;
return arr[top1+1];
}
}
//Function to remove an element from top of the stack2.
int pop2()
{
if(top2==size)
return -1;
else
{
top2++;
return arr[top2-1];
}
}
}