一、用队列实现栈
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
题解:
根据题意,要用两个队列来实现栈,首先我们知道,队列是先进先出,栈是后进先出。
知道了以上要点,我们两个队列的用处也就一目了然了。
一个队列为主队列,一个为辅助队列,当入栈操作时,我们先将主队列内容导入辅助队列,然后将入栈元素放入主队列队头位置,再将辅助队列内容,依次添加进主队列即可。
class MyStack {
private Queue<Integer> a;//输入队列
private Queue<Integer> b;//输出队列
public MyStack() {
a = new LinkedList<>();
b = new LinkedList<>();
}
public void push(int x) {
a.offer(x);
// 将b队列中元素全部转给a队列
while(!b.isEmpty())
a.offer(b.poll());
// 交换a和b,使得a队列没有在push()的时候始终为空队列
Queue temp = a;
a = b;
b = temp;
}
public int pop() {
return b.poll();
}
public int top() {
return b.peek();
}
public boolean empty() {
return b.isEmpty();
}
}
使用一个队列的实现方法
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
//模拟入栈操作
public void push(int x) {
queue.offer(x);
//将之前的全部都出队,然后再入队
for(int i = 1;i<queue.size();i++){
queue.offer(queue.poll());
}
}
//模拟出栈
public int pop() {
return queue.poll();
}
//返回栈顶元素
public int top() {
return queue.peek();
}
//判断是否为空
public boolean empty() {
return queue.isEmpty();
}
}
二、用栈实现队列
class MyQueue {
private Stack<Integer> a;// 输入栈
private Stack<Integer> b;// 输出栈
public MyQueue() {
a = new Stack<>();
b = new Stack<>();
}
public void push(int x) {
a.push(x);
}
public int pop() {
// 如果b栈为空,则将a栈全部弹出并压入b栈中,然后b.pop()
if(b.isEmpty()){
while(!a.isEmpty()){
b.push(a.pop());
}
}
return b.pop();
}
public int peek() {
if(b.isEmpty()){
while(!a.isEmpty()){
b.push(a.pop());
}
}
return b.peek();
}
public boolean empty() {
return a.isEmpty()&&b.isEmpty();
}
}