leetcode之Implement Queue using Stacks

C++标准里面对于栈,总共就给出了四种操作:入栈push,出栈pop,检查是否为空empty,返回栈的顶top。

本题考查用栈的四种操作组合来实现队列queue的操作,可谓考查数据结构的基本功。解决方法之一是,使用两个栈,一个负责“进”,另一个负责“出”。

难点是队列的出队操作,也就是pop,当负责“”的栈是空的时候同时负责进的栈非空,则此时先将负责“进”的栈的所有元素依次全部pop出来再依次全部push进负责“出”的栈中。这样再执行负责“出”的栈的pop操作。

C++代码如下:

class Queue {
public:
    stack<int> stk1;
    stack<int> stk2;
    // Push element x to the back of queue.
    void push(int x) {
        stk1.push(x);
    }


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


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


    // Return whether the queue is empty.
    bool empty(void) {
        return stk1.empty()&&stk2.empty();
    }
};

java代码如下:

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


    // Removes the element from in front of queue.
    public void pop() {
        peek();
        stk2.pop();
    }


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


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值