在C语言中,可以通过使用数组和指针来创建一个栈数据结构。下面是一个简单的示例代码:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int top;
} Stack;
Stack* createStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->top = -1;
return stack;
}
int isEmpty(Stack* stack) {
return stack->top == -1;
}
int isFull(Stack* stack) {
return stack->top == MAX_SIZE - 1;
}
void push(Stack* stack, int value) {
if (isFull(stack)) {
printf("Stack is full\n");
return;
}
stack->data[++stack->top] = value;
}
int pop(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1;
}
return stack->data[stack->top--];
}
int peek(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1;
}
return stack->data[stack->top];
}
int main() {
Stack* stack = createStack();
push(stack, 1);
push(stack, 2);
push(stack, 3);
printf("Top element: %d\n", peek(stack));
printf("Popped element: %d\n", pop(stack));
printf("Popped element: %d\n", pop(stack));
printf("Top element: %d\n", peek(stack));
return 0;
}
在这个示例代码中,我们定义了一个Stack结构体,包含一个整型数组data和一个整型top表示栈顶元素的索引。通过createStack函数来创建一个栈,isEmpty和isFull函数来判断栈是否为空或满,push函数用来入栈,pop函数用来出栈,peek函数用来查看栈顶元素。在主函数中我们演示了如何使用这些函数操作栈。