0
点赞
收藏
分享

微信扫一扫

力扣刷题-225用队列实现栈

题目

方法

image.png

思路

用两个队列,其实就是将队列2当作辅助队列,将队列元素出队顺序与栈中元素出栈顺序弄成一致,这样就可以正常出栈。

class MyStack {

Queue<Integer> queue1;
Queue<Integer> queue2; //辅助队列

public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}

public void push(int x) {
queue2.offer(x); //放在辅助队列
while(!queue1.isEmpty()){
queue2.offer(queue1.poll());
}
Queue<Integer> queueTemp;
queueTemp = queue1;
queue1 = queue2;
queue2 = queueTemp; //交换1和2 ,将元素放到queue1中
}

public int pop() {
return queue1.poll();
}

public int top() {
return queue1.peek();
}

public boolean empty() {
return queue1.isEmpty();
}
}

ce0f9e30263b8e29b275abaf4df57ee.jpg

优化

将两个队列转化为1个队列,相当于在一个队列里取出元素再入队。这个代码还没看懂,看懂再添加

举报

相关推荐

0 条评论