1.2 顺序栈

1.2 顺序栈_哔哩哔哩_bilibili

 

//顺序栈的实现 C++编译
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

#define MaxSize 10 //栈的容量

//顺序栈的类型定义
typedef struct{
    int data[MaxSize]; //静态数组存放栈中元素
    int top;           //栈顶指针
}SqStack;

//初始化栈
void InitStack(SqStack &S){
    S.top=-1;
}

//判断栈是否为空
bool StackEmpty(SqStack S){
    return S.top==-1;
}

//判断栈是否已满
bool StackFull(SqStack S){
    return S.top==MaxSize-1;
}

//进栈
void Push(SqStack &S, int e){
    if(StackFull(S)) return;
    S.data[++S.top]=e;
}

//出栈
void Pop(SqStack &S, int &e){
    if(StackEmpty(S)) return;
    e=S.data[S.top];
    S.top--;
}

//读栈顶
int GetTop(SqStack S){
    if(!StackEmpty(S))
        return S.data[S.top];
}
int main(){
    SqStack S; //声明顺序栈
    InitStack(S); //初始化
    int n=3; int a[]={0,2,5};
    for(int i=0;i<n;i++){
        Push(S,a[i]);
    }
    for(int i=0,e;i<n;i++){
        Pop(S,e);
        printf("%d ",e);
    }
    return 0;
}

 

 

.

posted @ 2026-09-09 07:00  董晓  阅读(23)  评论(0)    收藏  举报