File tree 1 file changed +62
-0
lines changed
1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ // Implement the following operations of a stack using queues.
3
+
4
+ // push(x) -- Push element x onto stack.
5
+ // pop() -- Removes the element on top of the stack.
6
+ // top() -- Get the top element.
7
+ // empty() -- Return whether the stack is empty.
8
+ */
9
+
10
+ class MyStack {
11
+
12
+ private Queue<Integer> value = new LinkedList<>();
13
+ private Queue<Integer> temp = new LinkedList<>();
14
+ private int top;
15
+
16
+ /** Initialize your data structure here. */
17
+ public MyStack() {
18
+
19
+ }
20
+
21
+ /** Push element x onto stack. */
22
+ public void push(int x) {
23
+ value.add(x);
24
+ top = x;
25
+ }
26
+
27
+ /** Removes the element on top of the stack and returns that element. */
28
+ public int pop() {
29
+ while (value.size() > 1) {
30
+ top = value.remove();
31
+ temp.add(top);
32
+ }
33
+
34
+ int element = value.remove();
35
+
36
+ while (temp.size() > 0) {
37
+ top = temp.remove();
38
+ value.add(top);
39
+ }
40
+
41
+ return element;
42
+ }
43
+
44
+ /** Get the top element. */
45
+ public int top() {
46
+ return top;
47
+ }
48
+
49
+ /** Returns whether the stack is empty. */
50
+ public boolean empty() {
51
+ return value.isEmpty();
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Your MyStack object will be instantiated and called as such:
57
+ * MyStack obj = new MyStack();
58
+ * obj.push(x);
59
+ * int param_2 = obj.pop();
60
+ * int param_3 = obj.top();
61
+ * boolean param_4 = obj.empty();
62
+ */
You can’t perform that action at this time.
0 commit comments