ITPub博客

首页 > IT职业 > IT职场 > [剑指offer] 用两个栈实现队列

[剑指offer] 用两个栈实现队列

IT职场 作者:Hooman 时间:2021-09-09 10:15:43 0 删除 编辑

题目描述

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

解题思路

两个栈 stack1 和 stack2:

  • push 动作都在 stack1 中进行,

  • pop 动作在 stack2 中进行。当 stack2 不为空时,直接 pop,当 stack2 为空时,先把 stack1 中的元素 pop 出来,push 到 stack2 中,再从 stack2 中 pop 元素。

参考代码

import java.util.Stack;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.isEmpty() && stack2.isEmpty())            throw new RuntimeException("Queue is empty!");        int node;        if(stack2.isEmpty()){            while(!stack1.isEmpty()){
                node = stack1.pop();
                stack2.push(node);
            }
        }        return stack2.pop();
        
    }
}



作者:繁著
链接:https://www.jianshu.com/p/5ebedf575cd4


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1273/viewspace-2819231/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    120
  • 访问量
    1202