栈和队列相关

栈的顺序存储结构

复制代码
#define maxsize 50
typedef int ElemType;
typedef struct {
    ElemType data[maxsize];
    int top;
}SqStack;

顺序栈的基本算法

初始化栈

cpp 复制代码
void InitStack(SqStack *s){
    s.top=-1;
    return;
}

判断栈空

cpp 复制代码
bool IsEmptyStack(SqStack *s){
    if(s.top==-1){
        return true;
    }else{
        return false;
    }
}

进栈

cpp 复制代码
bool Push(SqStack *s,ElemType e){
    if(s.top==maxsize-1){           //栈满
        return false;
    }else{
        s.top++;
        s.data[s.top]=e;
        return true;
    }
}

出栈

cpp 复制代码
bool Pop(SqStack *s,ElemType &e){
    if(IsEmptyStack(s)){           //栈空
        return false;
    }else{
        e=s.data[s.top];
        s.top--;
        return true;
    }
}

读栈顶元素

cpp 复制代码
bool GetTop(SqStack *S,ElemType &e){
    if(IsEmptyStack(s)){           //栈空
        return false;
    }else{
        e=s.data[s.top];
        return true;
    }
}

总代码

cpp 复制代码
#include <stdio.h>

#define maxsize 50
typedef int ElemType;
typedef struct {
    ElemType data[maxsize];
    int top;
}SqStack;

void InitStack(SqStack *s){
    s.top=-1;
    return;
}

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

bool Push(SqStack *s,ElemType e){
    if(s.top==maxsize-1){           //栈满
        return false;
    }else{
        s.top++;
        s.data[s.top]=e;
        return true;
    }
}

bool Pop(SqStack *s,ElemType &e){
    if(IsEmptyStack(s)){           //栈空
        return false;
    }else{
        e=s.data[s.top];
        s.top--;
        return true;
    }
}

bool GetTop(SqStack *S,ElemType &e){
    if(IsEmptyStack(s)){           //栈空
        return false;
    }else{
        e=s.data[s.top];
        return true;
    }
}
int main() {
    return 0;
}
相关推荐
AuroraWanderll4 小时前
类和对象(六)--友元、内部类与再次理解类和对象
c语言·数据结构·c++·算法·stl
leaves falling4 小时前
c语言-给定两个数,求这两个数的最大公约数
数据结构·算法
想做后端的小C4 小时前
数据结构:线性表原地逆置
数据结构·考研
jikiecui4 小时前
信奥崔老师:三目运算 (Ternary Operator)
数据结构·c++·算法
无限进步_4 小时前
【C语言&数据结构】另一棵树的子树:递归思维的双重奏
c语言·开发语言·数据结构·c++·算法·github·visual studio
志摩凛4 小时前
Element UI 长表单校验失败后自动展开折叠面板并滚动定位
数据结构·vue.js
一起努力啊~4 小时前
算法刷题--链表
数据结构·算法·链表
不被AI替代的BOT4 小时前
【实战】企业级物联网架构-元数据与物模型
数据结构·架构
郝学胜-神的一滴5 小时前
《机器学习》经典教材全景解读:周志华教授匠心之作的技术深探
数据结构·人工智能·python·程序人生·机器学习·sklearn