#include <stdio.h>
#include <stdbool.h>
#define SIZE 100
typedef struct {
int data[SIZE];
int top;
} Stack;
bool Empty(Stack* ps) {
return ps->top == -1;
}
bool isFull(Stack* ps) {
return ps->top == SIZE - 1;
}
void stackinit(Stack* ps) {
ps->top = -1;
}
void push(Stack* ps, int val) {
if (isFull(ps)) {
printf("栈满,无法入栈\n");
return;
}
ps->top++;
ps->data[ps->top] = val;
}
void pop(Stack* ps) {
if (Empty(ps)) {
printf("栈空,无法出栈\n");
return;
}
ps->top--;
}
int topElement(Stack* ps) {
if (!Empty(ps)) {
return ps->data[ps->top];
}
printf("栈空,无法获取栈顶元素\n");
return -1; // 返回一个错误码,表示栈为空
}
int main() {
Stack ps;
stackinit(&ps);
push(&ps, 1);
push(&ps, 2);
push(&ps, 3);
while (!Empty(&ps)) {
printf("%d ", topElement(&ps));
pop(&ps);
}
printf("\n");
return 0;
}
08-26
1690
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)