int main()
{
SeqStack MyStack;
StackInitiate(&MyStack);
for (int i = 0; i < 10; i++)
StackPush(&MyStack, i);
printf("栈顶元素为:%d\n", StackTop(&MyStack));
int pop;
StackPop(&MyStack, &pop);
printf("%d 已出栈\n", pop);
printf("栈顶元素为:%d\n", StackTop(&MyStack));
//依次出栈
while (StackNotEmpty(MyStack)) {
StackPop(&MyStack, &pop);
printf("%d ", pop);
}
//判断全部出栈后是否为空
if (!StackNotEmpty(MyStack))
printf("栈已空\n");
return 0;
}
输出:
SeqStack.h头文件
(点击下载)
#include "stdio.h"
#define DataType int
#define MaxStackSize 100
typedef struct {
DataType stack[MaxStackSize];
int top;
}SeqStack;
//初始化
void StackInitiate(SeqStack *S) {
S->top = 0;
}
//非空否
int StackNotEmpty(SeqStack S) {
if (S.top == 0)
return 0;
else return 1;
}
//入栈
int StackPush(SeqStack *S, DataType x) {
if (S->top >= MaxStackSize) {
printf("堆栈已满,无法入栈!");
return 0;
}
else {
S->stack[S->top] = x;
S->top++;
return 1;
}
}
//出栈
int StackPop(SeqStack *S, DataType *x) {
if (S->top <= 0) {
printf("堆栈以空,无法出栈");
return 0;
}
else {
S->top--;
*x = S->top;
return 1;
}
}
//取栈顶元素
int StackTop(SeqStack *S) {
if (S->top <= 0) {
printf("堆栈以空");
return -1;
}
else {
return S->stack[S->top - 1];
}
}