LeetCode Implement Queue using Stacks

54 篇文章 0 订阅
16 篇文章 0 订阅

原题链接在这里:https://leetcode.com/problems/implement-queue-using-stacks/

本题与Implement Stack using Queues相对应。

用Stack implement queue时,可以采用两个stack,add时就是一直像stk1中压栈。

poll()时把stk1的所有元素逐个压入另一个stack stk2中,现在stk2最上面的元素就是最先来的的,pop()之后再把剩下的压回到stk1中。

peek()与poll()类似,但这次不用pop(), 只需peek()出一个值返回。

Note: 1. 中间peek()时 用到了int res = stk2.peek(); 

所以生成stack时一定要加上类型<Integer>, if using Stack stk2 = new Stack(), it will throw error.

AC Java:

class MyQueue {
    // Push element x to the back of queue.
    private Stack<Integer> stk1 = new Stack<Integer>();
    private Stack<Integer> stk2 = new Stack<Integer>();
    public void push(int x) {
        stk1.push(x);
    }

    // Removes the element from in front of queue.
    public void pop() {
        while(!stk1.empty()){
            stk2.push(stk1.pop());
        }
        stk2.pop();
        while(!stk2.empty()){
            stk1.push(stk2.pop());
        }
    }

    // Get the front element.
    public int peek() {
        while(!stk1.empty()){
            stk2.push(stk1.pop());
        }
        int res = stk2.peek();
        while(!stk2.empty()){
            stk1.push(stk2.pop());
        }
        return res;
    }

    // Return whether the queue is empty.
    public boolean empty() {
        return stk1.empty();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值