-
-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathMyStack.java
More file actions
42 lines (32 loc) · 784 Bytes
/
Copy pathMyStack.java
File metadata and controls
42 lines (32 loc) · 784 Bytes
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
package leetcode.easy;
import java.util.LinkedList;
import java.util.Queue;
public class MyStack {
private Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.add(x);
for (int i = 1; i < queue.size(); i++)
queue.add(queue.remove());
}
public int pop() {
return queue.remove();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
public static void main(String[] args) {
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
System.out.println(stack.top()); // returns 2
stack.pop();
System.out.println(stack.pop()); // returns 1
System.out.println(stack.empty()); // returns false
}
}