232. Implement Queue using Stacks

题目:

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.
Notes:
  • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
思路:

用两个栈来模拟队列,详情的思路请看代码中的注释,对自己无奈的是没有使用Stack这个结构,而是用ArrayList。。。


代码:

class MyQueue {
    //用两个栈来模拟一个队列,用ArrayList模拟栈
    ArrayList<Integer> stack1 = new ArrayList<Integer>();
    ArrayList<Integer> stack2 = new ArrayList<Integer>();
    
    // Push element x to the back of queue.
    // 添加元素时就添加到栈1中
    public void push(int x) {
        stack1.add(x);
    }

    // Removes the element from in front of queue.
    /* 当删除元素时候,就需要用到栈2了
     * 若栈2为空,将栈1中的元素逐一弹出再依次压入栈2,这样就保证先入栈的元素位于栈2的栈顶,再栈2的栈顶元素
     * 若栈2不为空,则表示栈2中的元素均先于栈1中的元素入栈,因此直接弹出栈2的栈顶元素
    */
    public void pop() {
        int cur, tmp;
        if(!stack2.isEmpty()){
            stack2.remove(stack2.size()-1);
        }else{
            while(!stack1.isEmpty()){
                cur = stack1.size()-1;
                tmp = stack1.get(cur);
                stack1.remove(cur);
                stack2.add(tmp);
            }
            stack2.remove(stack2.size()-1);
        }
    }

    // Get the front element.
    // 原理类似于删除元素
    public int peek() {
        int cur, tmp, val;
        if(!stack2.isEmpty()){
            val = stack2.get(stack2.size()-1);
        }else{
            while(!stack1.isEmpty()){
                cur = stack1.size()-1;
                tmp = stack1.get(cur);
                stack1.remove(cur);
                stack2.add(tmp);
            }
            val = stack2.get(stack2.size()-1);
        }
        return val;
    }

    // Return whether the queue is empty.
    // 只有栈1和栈2都是空的时候才是空
    public boolean empty() {
        if(stack1.isEmpty() && stack2.isEmpty()){
            return true;
        }else{
            return false;
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值