class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
public MyQueue() {
// 负责进栈
stackIn = new Stack<>();
// 负责出栈
stackOut = new Stack<>();
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
dumpstackIn();
return stackOut.pop();
}
public int peek() {
dumpstackIn();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
// 如果stackout为空,将stackin中的元素全部放入stackout中
public void dumpstackIn() {
if (!stackOut.isEmpty()) {
return;
}
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
}
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.add(x);
}
public int pop() {
int size = queue.size();
size--;
while (size-- > 0) {
queue.add(queue.poll());
}
return queue.poll();
}
public int top() {
int size = queue.size();
size--;
while (size-- > 0) {
queue.add(queue.poll());
}
int result = queue.poll();
queue.add(result);
return result;
}
public boolean empty() {
return queue.isEmpty();
}
}
今天题目不难,主要熟悉了栈的api