#include <stdio.h>
#include <stdlib.h>
#define MaxSize 50 //定义栈中元素最大个数
typedef int ElemType;
typedef struct Stack {
ElemType data[MaxSize]; //存放栈中元素
int top; //栈顶指针
} Stack;
//初始化顺序栈
Stack* InitStack(Stack *S) {
S->top = -1; //初始化栈顶指针
return S;
}
//进栈操作
Stack* Push(Stack *S, ElemType x) {
if (S->top == MaxSize) //栈满,返回原栈
return S;
S->data[++S->top] = x; //指针先加1,再入栈
return S;
}
//出栈操作
int Pop(Stack *S) {
if (S->top == -1)
return -1;
int x = S->data[S->top--];
return x;
}
//读取栈顶元素
ElemType GetTop(Stack *S) {
int x;
if (S->top == -1) { //栈空,报错
return -1;
}
x = S->data[S->top];
return x;
}
int main() {
Stack S;
Stack *S1 = InitStack(&S);
Stack *S2 = Push(S1, 2);
Stack *S3 = Push(S2, 3);
int j = GetTop(S3);
printf("栈顶元素为:%d\n", j);
Pop(S3);
int i = GetTop(S3);
printf("栈顶元素为:%d", i);
}
顺序栈的基本操作 C语言版
最新推荐文章于 2022-10-12 20:14:16 发布