zoukankan      html  css  js  c++  java
  • 线性表之栈

    栈的定义:

      一种只能在一端进行插入或删除操作的线性表被称为栈,其中允许删除或插入的一端为栈顶,另一端为栈底,栈底固定不变;

      栈的特点:先进后出,例如弹夹,先装的子弹最后才能出;

      按照存储结构可以分为两种栈:

    • 顺序栈
    • 链式栈

    栈的结构体定义:

    顺序栈:

      

    //顺序栈的结构体定义
    typedef struct {
        int data[MaxSize];
        //栈顶指针
        int top;
    }SqStack;

    链式栈:

    //链栈结构体定义
    typedef struct LNode {
        int data;
        struct LNode* next;
    }LNode;

      ps:有没有发现链式栈和单链表定义一模一样;其实栈的本质就是受约束的线性表;

    基本算法:

    判断栈是否为空:

    bool IsEmptyS(SqStack s) {
        if (s.top == -1)
            return true;
        else
            return false;
    }

    栈是否为为满:

    bool IsFullS(SqStack s) {
        if (s.top == MaxSize - 1)
            return true;
        else
            return false;
    }

    栈的初始化:

    void InitialStack(SqStack &s) {
        //规定top=-1时为空栈
        s.top = -1;
    }

    入栈:

    bool push(SqStack &s, int x) {
        if (s.top == MaxSize - 1)
            return false;
        s.data[++s.top] = x;
        return true;
    }

    出栈:

    int pop(SqStack &s) {
        if (s.top == -1)
            return false;
        return s.data[s.top--];
        
    }

    打印整个栈:

    void PrintStack(SqStack s) {
        if (s.top == -1) {
            cout << "栈空,无法打印" << endl;
        }
        int i = s.top;
        for (i; i >= 0; i--) {
            cout << s.data[s.top--]<<"	";
        }
    
        cout << endl;
    }

    测试用例:

    int main()
    {
        
        int a[4] = { 1,2,3,4 };
        SqStack s;
        InitialStack(s);
        cout << "顺序栈测试" << endl;
        
        for (int i = 0; i < 4; i++) {
            push(s, a[i]);
        }
        PrintStack(s);
    
        cout << "2入栈" << endl;
        push(s, 2);
        cout << "10入栈" << endl;
        push(s, 10);
        PrintStack(s);
        cout << "出栈第一次	" << pop(s) << endl;
        cout << "出栈第二次	" << pop(s) << endl;
        cout << "出栈第三次	" << pop(s) << endl;
    
        PrintStack(s);
    
        system("pause");
        return 0;
    }
  • 相关阅读:
    html5 存储方式
    分割字符串得到分数,然后求和取整
    通过javascript的日期对象来得到当前的日期
    基础选择器
    制作3D旋转视频展示区
    自由缩放属性resize
    团队项目第四天
    团队项目第三天
    团队项目第二天
    团队项目第一天
  • 原文地址:https://www.cnblogs.com/zuixime0515/p/9613922.html
Copyright © 2011-2022 走看看