• 232.用栈实现队列 :::info 这是一道模拟题,不涉及到具体算法,考察的就是对栈和队列的掌握程度。 :::

    代码:(详细注释)

    1. class MyQueue {
    2. public:
    3. stack<int> stIn;
    4. stack<int> stOut;
    5. /** Initialize your data structure here. */
    6. MyQueue() {
    7. }
    8. /** Push element x to the back of queue. */
    9. void push(int x) {
    10. stIn.push(x);
    11. }
    12. /** Removes the element from in front of queue and returns that element. */
    13. int pop() {
    14. // 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
    15. if (stOut.empty()) {
    16. // 从stIn导入数据直到stIn为空
    17. while(!stIn.empty()) {
    18. stOut.push(stIn.top());
    19. stIn.pop();
    20. }
    21. }
    22. int result = stOut.top();
    23. stOut.pop();
    24. return result;
    25. }
    26. /** Get the front element. */
    27. int peek() {
    28. int res = this->pop(); // 直接使用已有的pop函数
    29. stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
    30. return res;
    31. }
    32. /** Returns whether the queue is empty. */
    33. bool empty() {
    34. return stIn.empty() && stOut.empty();
    35. }
    36. };

    分析:
    用栈实现队列 - 图1