栈系列之 用栈实现队列

算法专题导航页面


【算法专题 - 栈】

  1. 栈系列之 栈排序
  2. 栈系列之 最小栈的实现
  3. 栈系列之 用栈实现队列
  4. 栈系列之 递归实现一个栈的逆序

【题目】
   编写一个算法,用栈实现一个队列。

【其他限制】
  无。

【图示】
在这里插入图片描述
【分析】
  栈结构的特点是先进后出,队列结构的特点是先进先出。对于一个无序整数序列,使用两个栈,经过进栈->出栈->进栈->出栈操作,刚好可以得到原始无序整数序列,如上图所示。

【解决方案】
  具体思路:初始化两个栈StackPush和StackPop,前者仅负责入栈操作,后者仅负责出栈操作。需要注意,元素从StackPush压入StackPop中存在两个条件:
  a. StackPop非空时,禁止压入元素。
  b. 必须一次性全部压入,否则一旦积压,最终的出栈顺序将被打乱。

【代码实现】

/*
 * DESC:
 * A class implements a queue using two stacks
*/ 

public class StackQueue {
    private Stack<Integer> stackPush;
    private Stack<INteger> stackPop;
    public StackQueue() {
        this.stackPush = new Stack<Integer>();
        this.stackPop = new Stack<Integer>();
    }

    private void pushToStackPop() {
        if (this.stackPop.IsEmpty()) {
            while (!this.stackPush.IsEmpty())
                this.stackPop.push(this.stackPush.pop());
        }
    }

    // Add element to queue.
    // When adding elelment to StackPush, need to judge whether it's necessary to add it to stackPop simultaneously
    public void add( int element) {
        this.stackPush.push(element);
        pushToStackPop();
    }

    // Remove a element from queue
    public int poll() {
        if (this.StackPush.IsEmpty() && this.StackPop.IsEmpty())
            throw new RuntimeException('Queue is empty.');
        pushToStackPop();
        return this.stackPop.pop();
    }

    // Get the header element of queue
    public int peek() {
        if (this.StackPush.IsEmpty() && this.StackPop.IsEmpty())
            throw new RuntimeException('Queue is empty.');
        pushToStackPop();
        return this.stackPop.peek();    
    }
}
  • 6
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值