用两个栈实现队列

题目描述

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

时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M

一开始的思路:用stack1做push操作。当pop操作时,先将stack2中元素清空,然后将stack1中的数据全部放入stack2中,然后取出stack2栈顶元素,最后把stack2中剩下的元素又放回stack1中,代码如下:

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);
    }
    
    public int pop() {
      if(stack1.empty()) return 0;
      else{
        if(!stack2.empty()) stack2.clear();
        while(!stack1.empty()){
            int tem=stack1.pop();
            stack2.push(tem);
          } 
          int num= stack2.pop();       
         while(!stack2.empty()){
            int tem=stack2.pop();
            stack2.push(tem);
          } 
        return num;
       }
    
    }
}

但是运行后发现时间超时了。

问题在于每次出栈的时候都需要遍历全部元素两次,很耗时间。后来参考别人代码后,做了一些修改。当stack2为空时,需要把stack1中的全部元素放入stack2中,但是当stack2不为空时,只需要弹出stack2中的栈顶元素即可,这样就剩下了很多时间。代码如下:

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);
    }
    
    public int pop() {
      if(stack1.empty()&&stack2.empty())  throw new RuntimeException("Queue is empty!");
      else
      {
        if(stack2.empty())    //当stack2中没有元素时,需要将stack1中元素导入
        {
           while(!stack1.empty())
           {
            int tem=stack1.pop();
            stack2.push(tem);
           } 
           return stack2.pop();
        }
        else return stack2.pop();    //stack2不为空时,直接返回栈顶元素
        
       }
    
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值