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