栈——顺序存储

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);
} 
相关推荐
Xの哲學8 分钟前
深入剖析Linux文件系统数据结构实现机制
linux·运维·网络·数据结构·算法
C雨后彩虹33 分钟前
竖直四子棋
java·数据结构·算法·华为·面试
荒诞硬汉1 小时前
对象数组.
java·数据结构
散峰而望2 小时前
【算法竞赛】栈和 stack
开发语言·数据结构·c++·算法·leetcode·github·推荐算法
wen__xvn2 小时前
代码随想录算法训练营DAY13第六章 二叉树part01
数据结构
木子02042 小时前
Java8集合list.parallelStream() 和 list.stream() 区别
数据结构·list
Z1Jxxx3 小时前
0和1的个数
数据结构·c++·算法
ldccorpora3 小时前
Chinese News Translation Text Part 1数据集介绍,官网编号LDC2005T06
数据结构·人工智能·python·算法·语音识别
AuroraWanderll4 小时前
类和对象(六)--友元、内部类与再次理解类和对象
c语言·数据结构·c++·算法·stl