-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathImplementStackUsingQueues.java
More file actions
65 lines (53 loc) · 1.83 KB
/
Copy pathImplementStackUsingQueues.java
File metadata and controls
65 lines (53 loc) · 1.83 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
63
64
65
// Implement the following operations of a stack using queues.
// - push(x) -- Push element x onto stack.
// - pop() -- Removes the element on top of the stack.
// - top() -- Get the top element.
// - empty() -- Return whether the stack is empty.
// See: https://leetcode.com/problems/implement-stack-using-queues/
package leetcode.design;
import java.util.LinkedList;
import java.util.Queue;
public class ImplementStackUsingQueues {
class MyStack {
private Queue<Integer> q1 = new LinkedList<Integer>();
private Queue<Integer> q2 = new LinkedList<Integer>();
private int top = 0;
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
top = x;
q1.add(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int size = q1.size();
for (int i = 0; i < size - 1; i++)
q2.add(q1.poll());
int res = q1.poll();
for (int i = 0; i < size - 1; i++) {
if (i == size - 2) top = q2.peek();
q1.add(q2.poll());
}
return res;
}
/** Get the top element. */
public int top() {
return top;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty();
}
}
public static void main(String[] args) {
MyStack sln = new ImplementStackUsingQueues().new MyStack();
sln.push(1);
sln.push(2);
sln.push(3);
System.out.println(sln.top());
System.out.println(sln.pop());
System.out.println(sln.pop());
}
}