leetcode:面试题09. 用两个栈实现队列

题目解析

这道题和面试题 03.04. 化栈为队是几乎一样的:

定义两个栈:

  • 读栈rStack
  • 写栈wStack

操作:

  • appendTail: 直接压入wStack
  • deleteHead:
    • 如果rStack为空&&wStack为空,返回-1;
    • 如果rStack不为空,返回rStack.pop()
    • 如果rStack为空&&wStack不为空,将wStack全部压入rStack,然后rStack.pop()

cpp

class CQueue {
private:
    std::stack<int> r_stack;
    std::stack<int> w_stack;
public:
    CQueue() {

    }

    void appendTail(int value) {
        w_stack.push(value);
    }

    int deleteHead() {
        if(w_stack.empty() && r_stack.empty()){
            return -1;
        }
        if(r_stack.empty()){
            while (!w_stack.empty()){
                r_stack.push(w_stack.top());
                w_stack.pop();
            }
        }
        
        int bk = r_stack.top();
        r_stack.pop();
        return bk;
    }
};

leetcode:面试题09. 用两个栈实现队列_第1张图片

java

class CQueue {
    private Stack<Integer> wStack;
    private Stack<Integer> rStack;


    public CQueue() {
        wStack = new Stack<>();
        rStack = new Stack<>();
    }

    public void appendTail(int value) {
        wStack.push(value);
    }

    public int deleteHead() {
        if (wStack.empty() && rStack.empty()){
            return  -1;
        }
        
        if (rStack.empty()){
            while (!wStack.empty()){
                rStack.push(wStack.pop());
            }
        }
        
        return rStack.pop();
    }
}

在这里插入图片描述

你可能感兴趣的:(算法与数据结构,leetcode,链表,算法)