栈——顺序存储

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);
} 
相关推荐
hh随便起个名2 小时前
力扣二叉树的三种遍历
javascript·数据结构·算法·leetcode
xie_pin_an4 小时前
深入浅出 C 语言数据结构:从线性表到二叉树的实战指南
c语言·数据结构·图论
tang&4 小时前
滑动窗口:双指针的优雅舞步,征服连续区间问题的利器
数据结构·算法·哈希算法·滑动窗口
Nandeska6 小时前
2、数据库的索引与底层数据结构
数据结构·数据库
又是忙碌的一天7 小时前
二叉树的构建与增删改查(2) 删除节点
数据结构
Code Slacker7 小时前
LeetCode Hot100 —— 滑动窗口(面试纯背版)(四)
数据结构·c++·算法·leetcode
F_D_Z9 小时前
最长连续序列(Longest Consecutive Sequence)
数据结构·算法·leetcode
WolfGang0073219 小时前
代码随想录算法训练营Day50 | 拓扑排序、dijkstra(朴素版)
数据结构·算法
一直都在5729 小时前
数据结构入门:二叉排序树的删除算法
数据结构·算法
hweiyu009 小时前
排序算法简介及分类
数据结构