[Lintcode]Implement Queue by Two Stacks

本文介绍了一种使用两个栈来实现队列的方法。通过这种方式,可以有效地支持队列的基本操作,如push、pop和top。当执行pop或top操作时,如果出栈为空,则将入栈的所有元素依次移至出栈。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

As the title described, you should only use two stacks to implement a queue's actions.

The queue should support push(element)pop() and top()where pop is pop the first(a.k.a front) element in the queue.

Both pop and top methods should return the value of first element.

解法:双stack,一个进一个出。Empty时不需要单独处理,抛出stack抛出的异常即可

public class Queue {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;

    public Queue() {
        //out
       stack1 = new Stack<Integer>();
       //in
       stack2 = new Stack<Integer>();
    }
    
    public void push(int element) {
        stack2.push(element);
    }

    public int pop() {
        if(stack1.isEmpty()) {
            while(!stack2.isEmpty()) stack1.push(stack2.pop());
        } 
        return stack1.pop();
    }

    public int top() {
        if(stack1.isEmpty()) {
            while(!stack2.isEmpty()) stack1.push(stack2.pop());
        } 
        return stack1.peek();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值