用栈实现队列
class MyQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
private int front; //记录队首元素
/** Initialize your data structure here. */
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
if(stack1.isEmpty()){
front = x;
}
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(empty()){
return -1;
}
if(stack2.isEmpty()){
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
/** Get the front element. */
public int peek() {
if(stack2.isEmpty()){
return front;
}
return stack2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return (stack1.isEmpty()) && (stack2.isEmpty());
}
}
用队列实现栈
class MyStack {
private Queue<Integer> queue1;
private Queue<Integer> queue2;
/** Initialize your data structure here. */
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
queue1.offer(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
if(empty()){
return -1;
}
while (queue1.size()>1){
queue2.offer(queue1.poll());
}
//交换着两个队列
int num = queue1.poll();
Queue<Integer> tmp = queue1;
queue1 = queue2;
queue2 = tmp;
return num;
}
/** Get the top element. */
public int top() {
while (queue1.size()>1){
queue2.offer(queue1.poll());
}
return queue1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return (queue1.isEmpty()) && (queue2.isEmpty());
}
}