leetcode刷题 用堆栈实现队列 C++
   
    
    
    问题描述
   
使用栈实现队列的下列操作:
    push(x) – 将一个元素放入队列的尾部。
    
    pop() – 从队列首部移除元素。
    
    peek() – 返回队列首部的元素。
    
    empty() – 返回队列是否为空。
   
    
    
    思路
   
堆栈操作时先入后出,为了实现队列的先入先出操作,就需要将先入先出的堆栈进行存储循序的颠倒,所以需要两个堆栈单元来实现队列操作,定义两个堆栈分别为输入堆栈,对应于push操作,输出堆栈,对应于pop操作。要想使得push的数据在堆栈底部,就需要将原堆栈清空保存在一个堆栈缓冲区,push在堆栈底部,然后再将缓存区的数据库压入新的堆栈。
    
    
    代码
   
class MyQueue {
public:
    /** Initialize your data structure here. */
         stack<int> instack;
        stack<int> outstack;
    MyQueue() {
       
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        
        while(!outstack.empty())
        {
            instack.push(outstack.top());
            outstack.pop();
        }
        outstack.push(x);
        while(!instack.empty())
        {
            outstack.push(instack.top());
            instack.pop();
        }
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
       int a = outstack.top();
       outstack.pop();
        return a;
        
    }
    
    /** Get the front element. */
    int peek() {
        return outstack.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return outstack.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();
 */
 
版权声明:本文为zkple原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
