栈——顺序存储

c 复制代码
#include<stdio.h>
#define MaxSize 10
//栈的所有操作时间复杂度都是O(1) 

//定义
typedef struct{
    int data[MaxSize];
    int top;    //栈顶指针,永远指向栈顶元素 
}SqStack;

//初始化,使栈顶指针指向-1 
void InitStack(SqStack &S){
    S.top=-1;
} 

//判断栈空
bool StackEmpty(SqStack S){
    if(S.top==-1)
        return true;
    else 
        return false;
}

//判断栈满 
bool StackFull(SqStack S){
    if(S.top==MaxSize-1)
        return true;
    else 
        return false;
}

//入栈,先判断栈满 
bool Push(SqStack &S,int x){
    if(S.top==MaxSize-1)    //判断栈满
        return false;    
    
    S.top++;
    S.data[S.top]=x;
    printf("%d入栈成功\n",x);
    return true;
} 

//出栈,先判断栈空 
bool Pop(SqStack &S,int &x){
    if(S.top==-1)
        return false;
        
    x=S.data[S.top];
    S.top--;
    printf("%d出栈成功\n",x);
    return true;
}

//读取栈顶元素
bool GetTop(SqStack S,int &x){
    if(S.top==-1)
        return false;
        
    x=S.data[S.top];
    printf("栈顶元素是%d\n",x);
    return true;
} 
int main(){
    SqStack S;    //定义 
    InitStack(S);    //初始化 
    Push(S,1);    //入栈 
    Push(S,2);
    int x;        
    GetTop(S,x);     //读栈顶元素 
    Pop(S,x);        //出栈 
    GetTop(S,x);
} 
相关推荐
wdfk_prog18 分钟前
[Linux]学习笔记系列 -- lib/timerqueue.c Timer Queue Management 高精度定时器的有序数据结构
linux·c语言·数据结构·笔记·单片机·学习·安全
zhuzhuxia⌓‿⌓21 分钟前
线性表的顺序和链式存储
数据结构·c++·算法
高山有多高1 小时前
栈:“后进先出” 的艺术,撑起程序世界的底层骨架
c语言·开发语言·数据结构·c++·算法
YouEmbedded1 小时前
解码查找算法与哈希表
数据结构·算法·二分查找·散列表·散列查找·线性查找
小秋学嵌入式-不读研版2 小时前
C61-结构体数组
c语言·开发语言·数据结构·笔记·算法
Nix Lockhart3 小时前
《算法与数据结构》第七章[算法3]:图的最小生成树
c语言·数据结构·算法
丰锋ff3 小时前
2013 年真题配套词汇单词笔记(考研真相)
笔记·学习·考研
拾光Ծ5 小时前
【C++】STL有序关联容器的双生花:set/multiset 和 map/multimap 使用指南
数据结构·c++·算法
西望云天6 小时前
The 2023 ICPC Asia Shenyang Regional Contest(2023沈阳区域赛CEJK)
数据结构·算法·icpc
zh_xuan7 小时前
LeeCode92. 反转链表II
数据结构·算法·链表·leecode