-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprob_225.java
106 lines (91 loc) · 2.7 KB
/
prob_225.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
98
99
100
101
102
103
104
105
106
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
public class prob_225 {
public static void main(String[] args) {
String[] actions = {"MyStack", "push", "push", "top", "pop", "empty"};
Integer[] integers = {null, 1, 2, null, null};
MyStack_1 myStack = null;
for (int i = 0; i < actions.length; i++) {
switch (actions[i]) {
case "MyStack" -> myStack = new MyStack_1();
case "push" -> myStack.push(integers[i]);
case "top" -> System.out.println(myStack.top());
case "pop" -> System.out.println(myStack.pop());
case "empty" -> System.out.println(myStack.empty());
default -> {
System.out.println("Invalid operation to perform on stack");
}
}
System.out.println(myStack);
}
}
}
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedBlockingQueue<>();
}
public void push(int x) {
Queue<Integer> tmpQueue = new LinkedBlockingQueue<>();
tmpQueue.add(x);
queue.forEach(integer -> {
tmpQueue.add(integer);
});
queue = tmpQueue;
}
public int pop() {
return queue.remove();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
@Override
public String toString() {
StringBuilder stackString = new StringBuilder();
stackString.append("MyStack: { ");
queue.forEach(integer -> {
stackString.append(integer);
stackString.append(",");
});
stackString.deleteCharAt(stackString.length()-1);
stackString.append(" }");
return stackString.toString();
}
}
class MyStack_1 {
Queue<Integer> queue;
public MyStack_1() {
queue = new LinkedBlockingQueue<>();
}
public void push(int x) {
queue.add(x);
for (int i = 1; i < queue.size(); i++) {
int tmp = queue.remove();
queue.add(tmp);
}
}
public int pop() {
return queue.remove();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
@Override
public String toString() {
StringBuilder stackString = new StringBuilder();
stackString.append("MyStack: { ");
queue.forEach(integer -> {
stackString.append(integer);
stackString.append(",");
});
stackString.deleteCharAt(stackString.length()-1);
stackString.append(" }");
return stackString.toString();
}
}