Day10算法训练营| 栈与队列

栈与队列基本知识

图片来自代码随想录网站

栈stack

是一种基本数据结构,遵循Last In First Out (LIFO,后进先出),支持的操作命令有

push()入栈:将元素添加至栈的顶部;

pop()出栈:从栈的顶部移出元素,并返回被移出的元素;

top()查看栈顶元素:获取栈的顶部元素,但不移出它

empty()判空:判断栈是否为空,即栈中是否包含元素

size()获取元素数量:获取栈中元素数量

队列queue

push() 入队enqueue: 添加元素到队列尾部

pop() 出队dequeue:从队列头部移出元素

front() 查看队头元素: 获取队列头部元素

back()查看队尾元素:获取队尾元素

empty() 判空

size() 判断大小

class MyQueue {
public:
    stack<int> stIn;  // 输入栈,用于存储队列的元素
    stack<int> stOut; // 输出栈,用于辅助实现队列的出队操作

    /** Initialize your data structure here. */
    // 构造函数
    MyQueue() {

    }

    /** Push element x to the back of queue. */
    void push(int x) {
        stIn.push(x); // 将元素 x 推入输入栈,实现队列的入队操作
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        // 只有当 stOut 为空的时候,再从 stIn 里导入数据(导入 stIn 全部数据)
        if (stOut.empty()) {
            // 从 stIn 导入数据直到 stIn 为空
            while(!stIn.empty()) {
                stOut.push(stIn.top()); // 将 stIn 的元素逐个导入 stOut,实现反序
                stIn.pop();             // 弹出已导入的元素
            }
        }
        int result = stOut.top(); // 获取stOut 的栈顶元素,即队列的队头元素
        stOut.pop();              // 弹出已返回的元素
        return result;            // 返回队头元素
    }

    /** Get the front element. */
    int peek() {
        int res = this->pop();   // 直接使用已有的 pop 函数获取队头元素
        // 通过 this 关键字引用对象的成员
        stOut.push(res);         // 因为 pop 函数弹出了元素 res,所以再添加回去,维护队列的状态
        return res;              // 返回队头元素
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return stIn.empty() && stOut.empty(); // 如果输入栈和输出栈都为空,则队列为空
    }
};

225. 用队列实现栈 - 力扣(LeetCode)

class MyStack {
public:
    queue<int> que;
    /** Initialize your data structure here. */
    MyStack() {

    }
    /** Push element x onto stack. */
    void push(int x) {
        que.push(x);
    }
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int size = que.size();
        size--;
        while (size--) { // 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
            que.push(que.front()); // que.front() 获取队列头部的元素,将其插入队列尾部
            que.pop();
        }
        int result = que.front(); // 此时弹出的元素顺序就是栈的顺序了
        que.pop();
        return result;
    }

    /** Get the top element. */
    int top() {
        return que.back();
    }

    /** Returns whether the stack is empty. */
    bool empty() {
        return que.empty();
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值