代码随想录栈1

本文详细介绍了两个C++类实现的特殊数据结构:MyQueue使用两个栈来实现在两端进行操作的队列功能,MyStack则是通过两个队列实现高效栈操作。作者展示了类的构造方法和主要操作函数,如push、pop、peek和empty等。
摘要由CSDN通过智能技术生成

222

class MyQueue {
private:
    stack<int> stackIn,stackOut;

public:
    MyQueue() {

    }
    
    void push(int x) {
        stackIn.push(x);
    }
    
    int pop() {
        if(stackOut.empty()){
            while(!stackIn.empty()){
            stackOut.push(stackIn.top());
            stackIn.pop();
            }
        }
        int res = stackOut.top();
        stackOut.pop();
        return res;
    }
    
    int peek() {
        int res = this->pop();
        stackOut.push(res);
        return res;
    }
    
    bool empty() {
        return stackIn.empty() && stackOut.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();
 */

225

class MyStack {
private:
    queue<int> q1;
    queue<int> q2;

public:
    MyStack() {

    }
    
    void push(int x) {
         q1.push(x);  
    }
    
    int pop() {
         // 当q2为空时,将q1中的元素除了最后一个外都转移到q2  
        if (q2.empty()) {  
            while (q1.size() > 1) {  
                q2.push(q1.front());  
                q1.pop();  
            }  
        }  
          
        // q1的最后一个元素即为栈顶元素,弹出并返回  
        int topElement = q1.front();  
        q1.pop();  
          
        // 交换q1和q2的角色,确保下一次pop操作可以快速执行  
        swap(q1, q2);  
          
        return topElement;  

    }
    
    int top() {
        return q1.back();  

    }
    
    bool empty() {
        return q1.empty();
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值