顺序栈的C语言实现
#include <stdio.h>
#define MaxSize 50
#define ElemType int
typedef struct {
ElemType data[MaxSize];
int top;
} SqStack;
void InitStack(SqStack &s) {
s.top = -1;
}
bool StackEmpty(SqStack s) {
if (s.top == -1) {
return true;
} else {
return false;
}
}
void Push(SqStack &s, ElemType x) {
if (s.top == MaxSize - 1) {
printf("栈已满,无法入栈!\n");
}
s.data[++s.top] = x;
printf("%d已入栈!\n", x);
}
void Pop(SqStack &s) {
ElemType x;
if (s.top == -1) {
printf("栈空,无法出栈!\n");
}
x = s.data[s.top--];
printf("%d已出栈!\n", x);
}
ElemType GetTop(SqStack s) {
ElemType x;
if (s.top == -1) {
return -1;
}
x = s.data[s.top];
return x;
}
void PrintStack(SqStack s) {
printf("栈内元素:");
for (int i = 0; i <= s.top; i++) {
printf("%d ", s.data[i]);
}
printf("\n");
}
int main() {
SqStack s;
InitStack(s);
Push(s, 2);
Push(s, 3);
Push(s, 4);
Push(s, 5);
Pop(s);
Pop(s);
PrintStack(s);
printf("栈顶元素:%d\n", GetTop(s));
return 0;
}