#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10
struct Stack {
int items[MAX_SIZE];
int top;
};
void initStack(struct Stack *s) {
s->top = -1;
}
int isEmpty(struct Stack *s) {
return s->top == -1;
}
int isFull(struct Stack *s) {
return s->top == MAX_SIZE - 1;
}
void push(struct Stack *s, int value) {
if (isFull(s)) {
printf("Stack overflow\n");
return;
}
s->items[++s->top] = value;
}
int pop(struct Stack *s) {
if (isEmpty(s)) {
printf("Stack underflow\n");
return -1;
}
return s->items[s->top--];
}
int peek(struct Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty\n");
return -1;
}
return s->items[s->top];
}
int main() {
struct Stack s;
initStack(&s);
push(&s, 10);
push(&s, 20);
push(&s, 30);
printf("Top element: %d\n", peek(&s));
printf("Elements: ");
while (!isEmpty(&s)) {
printf("%d ", pop(&s));
}
printf("\n");
return 0;
}
一个使用数组作为存储结构的栈,并提供了初始化栈、判断栈空和栈满、入栈、出栈以及获取栈顶元素等基本操作。
发表评论 取消回复