Leetcode 232 用栈实现队列
class MyQueue {
private Stack<Integer> s1 = new Stack<>();
private Stack<Integer> s2 = new Stack<>();
public MyQueue() {
}
public void push(int x) {
s1.push(x);
}
public int pop() {
if(empty()) {
return -1;
}
if(s2.empty()) {
while(!s1.empty()) {
s2.push(s1.pop());
}
}
return s2.pop();
}
public int peek() {
if(empty()) {
return -1;
}
if(s2.empty()) {
while(!s1.empty()) {
s2.push(s1.pop());
}
}
return s2.peek();
}
public boolean empty() {
return s1.empty() && s2.empty();
}
}
Leetcode 225 用队列实现栈
class MyStack {
private Queue<Integer> qu1 = new LinkedList<>();
private Queue<Integer> qu2 = new LinkedList<>();
public MyStack() {
}
public void push(int x) {
if(!qu1.isEmpty()) {
qu1.offer(x);
} else if(!qu2.isEmpty()) {
qu2.offer(x);
} else {
qu1.offer(x);
}
}
public int pop() {
if(empty()) {
return -1;
}
int tmp = -1;
if(!qu1.isEmpty()) {
int size = qu1.size();
for(int i = 0; i < size - 1; i++) {
tmp = qu1.poll();
qu2.offer(tmp);
}
tmp = qu1.poll();
} else {
int size = qu2.size();
for(int i = 0; i < size - 1; i++) {
tmp = qu2.poll();
qu1.offer(tmp);
}
tmp = qu2.poll();
}
return tmp;
}
public int top() {
if(empty()) {
return -1;
}
int tmp = -1;
if(!qu1.isEmpty()) {
int size = qu1.size();
for(int i = 0; i < size; i++) {
tmp = qu1.poll();
qu2.offer(tmp);
}
} else {
int size = qu2.size();
for(int i = 0; i < size; i++) {
tmp = qu2.poll();
qu1.offer(tmp);
}
}
return tmp;
}
public boolean empty() {
return qu1.isEmpty() && qu2.isEmpty();
}
}