一,概述

栈和队列都是一种"操作受限"的线性表(逻辑结构),只允许在一端插入和删除数据;栈的特性是先进后出,队列是先进先出。在项目中当某个数据集合只涉及在一端插入和删除数据,并且满足后进先出、先进后出的特性,这时应当首选"栈"这种数据结构。

栈的实现有多种方式,可以用数组也可以用链表实现。基于数组实现的栈的C++代码如下:

class ArrayStack{
private:
    int items[];    // 定义一个数组
    int count;      // 栈中元素个数
    int n;          // 栈的大小

public:
    // 构造函数,利用数组初始化栈,栈的大小为 n
    ArrayStack(int n)  {
        this.items = new int[n];
        this.n = n;
        this.count = 0;
    }
    // 入栈操作
    bool push(int item){
        if(count == n) return False;
        // 将插入的元素 item 放在下标为 count 的位置,并且 count 加一
        items[count] = item;
        ++count;
        return True;
    }
    // 出栈操作
    bool pop(){
        if(count==0) return null;
        // 返回下标为 count-1 的数组元素,并且栈中元素减一
        int temp = items[count-1];
        --count;
        return temp;
    }
}

二,单调栈

单调栈模板题解法:单调栈解题模板秒杀八道题

参考资料

《数据结构与算法之美》-栈

Copyright © zhg5200211@outlook.com 2022 all right reserved,powered by Gitbook该文章修订时间: 2022-12-03 05:38:08

results matching ""

    No results matching ""

    results matching ""

      No results matching ""