第 1 天 栈与队列(简单)(之前的记录全没了,重新备份)

题目01:
剑指offer30

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int>stack1;
    stack<int>stack2;
    MinStack() {
        
    }
    
    void push(int x) {
        stack1.push(x);
        if(stack2.empty() || stack2.top()>=x)
            stack2.push(x);
    }
    
    void pop() {
        //保持 stack1 和stack2的一致性
        // 这里就不用重复压入stack2的顶部数据!
        int tmp1 = stack1.top();
        int tmp2 = stack2.top();
        stack1.pop();
        if(tmp1==tmp2){
            //stack1.pop();
            stack2.pop();
        }
        // return tmp2;
    }
    
    int top() {
        return stack1.top();
    }
    
    int min() {
        int temp = stack2.top();
        //stack2.pop();
        return temp;
    }
};

题目2:
剑指offer09

class CQueue {
public:
    CQueue() {
        
    }
    stack<int>stack1;
    stack<int>stack2;
    void appendTail(int value) {
        // 队尾插入 直接插入stack1
        
        stack1.push(value);
    }
    
    int deleteHead() {
        //如果stack2 就出栈
        //如果stack1不为空,就插入stack2
        if(!stack2.empty()){
            int temp = stack2.top();
            stack2.pop();
            return temp;
        }
        if(stack1.empty()) 
            return -1;
        
        while(!stack1.empty()){
            int tmp = stack1.top();
            stack2.push(tmp);
            stack1.pop();
        }
        int tm = stack2.top();
        stack2.pop();
        return tm;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值