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 top, peek/pop from top, size, 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).

s思路;
1. 继上次用queue实现stack,就讨论了stack和queue从某个角度看,就可以相互实现对方的功能,因为他们本身就有很多相似的操作但又相反的操作,如:push,pop,pop对stack来说是pop刚push进入的,而对queue来说是pop最早放进去的,都是弹出来,但是一个弹出最开头的一个数,一个弹出最结尾的一个数,所以是对称的。
2. 这回实现,就得用两个stack来实现一个queue,因为stack只有一个端口,进出都是这个端口,而queue有两个。同时,用stack模拟queue,意味着需要每次push进去的时候把当前值放在stack最底下,而不是最上面,所以需要用一个副stack,把主stack中的数全部读出放在副stack中,然后把当前数写到主stack的底部,再把副stack中的全部数据又读出压入主stack。思路就是分三步,和把大象装冰鞋里的步骤和思路都很像!

class MyQueue {
private:
    stack<int> ss1,ss2;
public:
    /** Initialize your data structure here. */
    MyQueue() {

    }

    /** Push element x to the back of queue. */
    void push(int x) {
        if(!ss1.empty()){
            while(!ss1.empty()){
                int cur=ss1.top();
                ss1.pop();
                ss2.push(cur);  
            }    
        }
        ss1.push(x);
        if(!ss2.empty()){
            while(!ss2.empty()){
                int cur=ss2.top();
                ss2.pop();
                ss1.push(cur);  
            }    
        }
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int res=ss1.top();
        ss1.pop();
        return res;
    }

    /** Get the front element. */
    int peek() {
        return ss1.top();
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return ss1.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();
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值