用栈实现对列

leetcode- 232.    用栈实现队列

相比于用队列实现栈,用栈实现队列能稍微麻烦一点。实现队列时需要两个栈来实现,左边的是出口,右边的是入口。

我们将数据压入right栈,然后出栈保存,进入left,再次出栈的顺序和进入right时的顺序就是一样的。

1.push(x) -- 将一个元素放入队列的尾部。

/** Push element x to the back of queue. */
    void push(int x) {
        right.push(x);
    }

2.pop() -- 从队列首部移除元素。

如果左边有元素,那么首部的元素就是left栈的栈顶,pop掉栈顶的元素就行。

如果左边没有,右边有元素,那么首部的元素就是right底部的元素,将所有的数据交换到left栈之后再pop掉栈顶的元素

如果都没有也是左边栈顶,返回值为空

/** Removes the element from in front of queue and returns that element. */
    int pop() {
        if(left.empty())
        {
            while(!right.empty())
            {
                int data = right.top();
                right.pop();
                left.push(data);
            }
        }
        int p = left.top();
        left.pop();
        return p;
    }

3.peek() -- 返回队列首部的元素。

如果左边有元素,那么首部的元素就是left栈的栈顶,返回栈顶的元素。

如果左边没有,右边有元素,那么首部的元素就是right底部的元素,将所有的数据交换到left栈之后返回栈顶元素

/** Get the front element. */
    int peek() {
       if(left.empty())
        {
            while(!right.empty())
            {
                int data = right.top();
                right.pop();
                left.push(data);
            }
        }
        return left.top();
    }

4.empty() -- 返回队列是否为空。

/** Returns whether the queue is empty. */
    bool empty() {
        if(left.empty()&&right.empty())
        {
            return true;
        }
        else
            return false;
    }

完整代码:

class MyQueue {
public:
    stack<int> left;
    stack<int> right;
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        right.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        if(left.empty())
        {
            while(!right.empty())
            {
                int data = right.top();
                right.pop();
                left.push(data);
            }
        }
        int p = left.top();
        left.pop();
        return p;
    }
    
    /** Get the front element. */
    int peek() {
       if(left.empty())
        {
            while(!right.empty())
            {
                int data = right.top();
                right.pop();
                left.push(data);
            }
        }
        return left.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        if(left.empty()&&right.empty())
        {
            return true;
        }
        else
            return false;
    }
};

/**
 * 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、付费专栏及课程。

余额充值