打卡20240119

关于字符串的1.17-1.18打卡周日再补,今天先把19号的任务做了~

栈:先进后出

相关接口:

void push(T);  //入栈   //T代表任意类型(就是stack容器的类型)
void pop(); //出栈  
T top();          //获取栈顶元素
bool empty();  //判断是否为空   为空返回true 否则返回false
int size();        // 统计栈内元素数量

队列:先进先出

empty:检测队列是否为空
size:返回队列中有效元素的个数
front:返回队头元素的引用
back:返回队尾元素的引用
push_back:在队列尾部入队列
pop_front:在队列头部出队列

232. 用栈实现队列

两个栈,一个做入栈,一个做出栈,形成队列。

class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;
    MyQueue() {

    }
    
    void push(int x) {
        stIn.push(x);
    }
    
    int pop() {
        if (stOut.empty()) {
            while (! stIn.empty()) {
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int result = stOut.top();
        stOut.pop();
        return result;
    }
    
    int peek() {
        if (stOut.empty()) {
            while (! stIn.empty()) {
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int result = stOut.top();
        return result;
    }
    
    bool empty() {
        if (stIn.empty() && stOut.empty()) return true;
        else return false;
    }
};

225. 用队列实现栈

这题用一个队列来实现栈的功能的思想很巧妙,不断将队列的队头元素插入队尾并删除,直到原本最开始的队列队尾元素截止,此时便是所谓的栈顶元素

class MyStack {
public:
    queue<int> que;
    MyStack() {

    }
    
    void push(int x) {
        que.push(x);
    }
    
    int pop() {
        int qSize = que.size() - 1;
        while (qSize) {
            que.push(que.front());
            que.pop();
            qSize--;
        }
        int result = que.front();
        que.pop();
        return result;
    }
    
    int top() {
        return que.back();
    }
    
    bool empty() {
        if (que.empty()) return true;
        else return false;
    }
};

/**
 * 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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值