《程序员面试金典(第6版)》面试题 03.04. 化栈为队

题目描述

实现一个MyQueue类,该类用两个栈来实现一个队列。

示例:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek();  // 返回 1
queue.pop();   // 返回 1
queue.empty(); // 返回 false

说明:

你只能使用标准的栈操作 – 也就是只有 push to top, peek/pop from top, size 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。

解题思路与代码

双栈法

这道题不难,只要你了解栈这种数据结构的用法就行。在C++中,栈其实是没有begin(),end()这种内置方法的。所以我们在往另一个栈中去放元素的时候,需要将第一个栈中的元素挨个取出,然后再压入第二个栈中。

所以,我们就可以写出如下操作,具体请看代码:

class MyQueue {
public:
    /** Initialize your data structure here. */
    stack<int> first;
    stack<int> second;
    MyQueue() {

    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        while(!second.empty()){
            int temp = second.top();
            second.pop();
            first.push(temp);
        }
        first.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        while(!first.empty()){
            int temp = first.top();
            second.push(temp);
            first.pop();
        }
        int temp = second.top();
        second.pop();
        return temp;
        
    }
    
    /** Get the front element. */
    int peek() {
        while(!first.empty()){
            int temp = first.top();
            second.push(temp);
            first.pop();
        }
        
        return second.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return first.empty() && second.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

复杂度分析:
时间复杂度:push()与empty()函数的时间复杂度为O(1),而pop()和peek()函数的时间复杂度均摊一下,也是O(1)。对于每个元素,最多出栈和入栈2次。故时间均摊复杂度为O(1)
空间复杂度:O(n)。其中n是操作总数,我们如果要向栈中push n个元素了话,那空间复杂度就是O(n)。

总结

这道题不亏为一道简单题,稍微想一下,就能写出来了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿宋同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值