《剑指offer》之用两个栈来实现一个队列

喜欢ヅ旅行 2023-07-03 03:16 85阅读 0赞

前言

今天刷的一道题是用两个栈来表示一个队列。
我们知道栈和队列的主要区别在于:
栈:后进先出
队列:先进先出。

题目

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

分析

需要通过两个后进先出的栈实现一个先进先出的队列。如下图:
在这里插入图片描述
假设往栈stack1 中压入 1,2,3,4,5,6,7 这几个数据,如果直接从stack1中取的话,就是7,6,5,4,3,2,1.与我们想要你的先进先出不符合。所以我们将stack1的数据依次出栈并压入栈stack2 中,这样再从stack2 中出栈的数据就是1,2,3,4,5,6,7了。
但是,上面的这些只考虑了先进栈后压栈。那如果是进栈出栈交替呢?
在这里插入图片描述
比如初始,向stack1 中压入 1,2,3.然后,将stack1 中的数据出栈入栈到stack2 中。
在这里插入图片描述
那这个时候,再往stack1 中进栈的话,该怎么压入栈stack2 中呢?
这里其实大家应该注意到,如果stack2 中存在数据,那这些数据应该是最先出栈的,所以直接出栈就好了,不用管stack1 中的数据,因为那些是后来的数据,肯定是是后出栈的。当栈stack2 中没有数据的时候,再将stack1 中的数据都出栈压入stack2 中。这样就可以实现一个队列的先进先出啦。

解法

进队列,直接将数据压入栈stack1 中就好了。

  1. public void push(int node){
  2. stack1.push(node);
  3. }

出队列,先判断stack2 中是否有数据,有的话,直接从stack2 中出栈。
如果没有,就将stack1 中的数据压入栈stack2 中。然后再从stack2 中出栈。

  1. public int pop(){
  2. if(!stack2.isEmpty()){
  3. return stack2.pop();
  4. }
  5. while(!stack1.isEmpty()){
  6. stack2.push(stack1.pop());
  7. }
  8. return stack2.pop();
  9. }

不过上面的代码还可以简化一下,毕竟两个return stack2.pop(); 有点不舒服。

  1. public int pop(){
  2. if(stack2.isEmpty()){
  3. while(!stack1.isEmpty()){
  4. stack2.push(stack1.pop());
  5. }
  6. }
  7. return stack2.pop();
  8. }

源代码:

  1. public class Solution {
  2. Stack<Integer> stack1=new Stack<>();
  3. Stack<Integer> stack2=new Stack<>();
  4. public static void main(String[] args) {
  5. Solution solution= new Solution();
  6. solution.push(0);
  7. solution.push(1);
  8. solution.push(2);
  9. solution.push(3);
  10. solution.push(4);
  11. solution.push(5);
  12. System.out.print(solution.pop()+"\t");
  13. System.out.print(solution.pop()+"\t");
  14. System.out.print(solution.pop()+"\t");
  15. solution.push(6);
  16. solution.push(7);
  17. solution.push(8);
  18. System.out.print(solution.pop()+"\t");
  19. System.out.print(solution.pop()+"\t");
  20. System.out.print(solution.pop()+"\t");
  21. }
  22. public void push(int node){
  23. stack1.push(node);
  24. }
  25. public int pop(){
  26. if(stack2.isEmpty()){
  27. while(!stack1.isEmpty()){
  28. stack2.push(stack1.pop());
  29. }
  30. }
  31. return stack2.pop();
  32. }
  33. }

测试

在这里插入图片描述
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,85人围观)

还没有评论,来说两句吧...

相关阅读