-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathQueue_using_two_Stacks.java
More file actions
62 lines (53 loc) · 1.33 KB
/
Queue_using_two_Stacks.java
File metadata and controls
62 lines (53 loc) · 1.33 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
// { Driver Code Starts
import java.util.*;
import java.util.Stack;
import java.util.LinkedList;
class GfG {
public static void main(String args[]) {
// Taking input using class Scanner
Scanner sc = new Scanner(System.in);
// Taking input the number of testcases
int t = sc.nextInt();
while (t > 0) {
// Creating a new object of class StackQueue
StackQueue g = new StackQueue();
// Taking input the total number of Queries
int q = sc.nextInt();
while (q > 0) {
int QueryTyoe = sc.nextInt();
// If QueryTyoe is 1 then
// we call the Push method
// of class StackQueue
// else we call the Pop method
if (QueryTyoe == 1) {
int a = sc.nextInt();
g.Push(a);
} else if (QueryTyoe == 2)
System.out.print(g.Pop() + " ");
q--;
}
System.out.println();
t--;
}
}
}
class StackQueue {
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
// Function to push an element in queue by using 2 stacks.
void Push(int x) {
s1.push(x);
}
int Pop() {
if (!s2.isEmpty()) {
return s2.pop();
} else {
if (s1.isEmpty())
return -1;
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
return s2.pop();
}
}
}