编写程序实现顺序栈的初始化、判断栈空否、入栈和出栈等,用c语言编写
时间: 2024-06-02 11:14:07 浏览: 103
用c语言来实现顺序栈
5星 · 资源好评率100%
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct Stack {
int data[MAX_SIZE];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_full(Stack *s) {
return s->top == MAX_SIZE - 1;
}
void push(Stack *s, int x) {
if (is_full(s)) {
printf("Error: Stack is full\n");
return;
}
s->top++;
s->data[s->top] = x;
}
int pop(Stack *s) {
if (is_empty(s)) {
printf("Error: Stack is empty\n");
return -1;
}
int x = s->data[s->top];
s->top--;
return x;
}
int main() {
Stack s;
init(&s);
push(&s, 1);
push(&s, 2);
push(&s, 3);
printf("%d\n", pop(&s)); // 3
printf("%d\n", pop(&s)); // 2
printf("%d\n", pop(&s)); // 1
printf("%d\n", pop(&s)); // Error: Stack is empty
return 0;
}
阅读全文