-
Notifications
You must be signed in to change notification settings - Fork 110
/
solution.java
60 lines (52 loc) · 1.76 KB
/
solution.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
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt(); // number of queries
Stack<Integer> ms = new Stack<Integer>(); // main stack
Stack<Integer> hs = new Stack<Integer>(); // helper stack
int command; // query type
for (int i = 0 ; i < q ; i++) {
command = in.nextInt();
if (command == 1)
{
// push value into main stack
ms.push(in.nextInt());
}
else if (command == 2)
{
if(hs.isEmpty())
{
// shift all elements from main stack to helper stack
while(!ms.isEmpty())
{
hs.push(ms.pop());
}
}
// pop from the helper stack
if (!hs.isEmpty()){
hs.pop();
}
}
else if (command == 3)
{
if(hs.isEmpty())
{
// shift all elements from main stack to helper stack
while(!ms.isEmpty())
{
hs.push(ms.pop());
}
// print top element of helper stack
System.out.println(hs.peek());
}
else
{
// print top element of helper stack
System.out.println(hs.peek());
}
}
}
}
}