以下是一个基本的顺序栈的C语言实现示例:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
int isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
void push(Stack *s, int value) {
if (isFull(s)) {
printf("Stack is full\n");
return;
}
s->top++;
s->data[s->top] = value;
}
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty\n");
return -1;
}
int value = s->data[s->top];
s->top--;
return value;
}
int peek(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty\n");
return -1;
}
return s->data[s->top];
}
int main() {
Stack stack;
initStack(&stack);
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
printf("Top element: %d\n", peek(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Is stack empty: %s\n", isEmpty(&stack) ? "true" : "false");
return 0;
}
这段代码定义了一个基本的顺序栈数据结构,包括初始化栈、判断栈是否为空或满、入栈、出栈、获取栈顶元素的操作。在main函数中,进行了栈的初始化、入栈、出栈等操作,并打印了一些信息。
您可以根据自己的需求对该代码进行修改和扩展。