forked from yubinbai/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyStack.java
More file actions
42 lines (36 loc) · 852 Bytes
/
MyStack.java
File metadata and controls
42 lines (36 loc) · 852 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
import java.util.*;
public class MyStack {
Queue<Integer> q;
public MyStack() {
q = new ArrayDeque();
}
// Push element x onto stack.
public void push(int x) {
q.offer(x);
}
// Removes the element on top of the stack.
public void pop() {
int n = q.size();
if (n == 0) return;
for (int i = 0; i < n - 1; ++i) {
int t = q.poll();
q.offer(t);
}
q.poll();
}
// Get the top element.
public int top() {
int n = q.size();
for (int i = 0; i < n - 1; ++i) {
int t = q.poll();
q.offer(t);
}
int result = q.poll();
q.offer(result);
return result;
}
// Return whether the stack is empty.
public boolean empty() {
return q.isEmpty();
}
}