栈——顺序存储

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);
} 
相关推荐
仰泳的熊猫7 小时前
题目2194:蓝桥杯2018年第九届真题-递增三元组
数据结构·c++·算法
啊哦呃咦唔鱼8 小时前
LeetCode hot100-15 三数之和
数据结构·算法·leetcode
leluckys8 小时前
算法-链表-二、成对交换两个节点
数据结构·算法·链表
随意起个昵称10 小时前
【贪心】选择尽量多的不相交区间
数据结构·算法
章小幽10 小时前
LeetCode-35.搜索插入位置
数据结构·算法·leetcode
j_xxx404_11 小时前
C++算法:一维/二维前缀和算法模板题
开发语言·数据结构·c++·算法
Book思议-12 小时前
顺序表和链表核心差异与优缺点详解
java·数据结构·链表
whn197714 小时前
在sqllog中排查达梦阻塞会话
数据结构
01二进制代码漫游日记14 小时前
C/C++中的内存区域划分
c语言·jvm·数据结构·学习
xiaoye-duck14 小时前
《算法题讲解指南:优选算法-链表》--51.两数相加,52.两两交换链表中的节点
数据结构·算法·链表