C语言实现栈数据结构代码示例
#include <stdio.h> #include <stdlib.h>
#define MAX_STACK_SIZE 100
typedef struct { int data[MAX_STACK_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_STACK_SIZE - 1; }
void push(Stack *s, int value) { if (is_full(s)) { printf('Error: stack is full\n'); exit(1); } s->data[++s->top] = value; }
int pop(Stack *s) { if (is_empty(s)) { printf('Error: stack is empty\n'); exit(1); } return s->data[s->top--]; }
int peek(Stack *s) { if (is_empty(s)) { printf('Error: stack is empty\n'); exit(1); } return s->data[s->top]; }
int main() { Stack s; init(&s);
push(&s, 1);
push(&s, 2);
push(&s, 3);
printf('%d\n', pop(&s));
printf('%d\n', peek(&s));
printf('%d\n', pop(&s));
printf('%d\n', pop(&s));
return 0;
}
上述代码实现了一个基本的栈数据结构,包含了初始化、判断栈是否为空或满、入栈、出栈、查看栈顶元素等基本操作。在main函数中,我们对栈进行了一些操作,如入栈1、2、3,出栈并打印栈顶元素等。
原文地址: https://www.cveoy.top/t/topic/n7Kc 著作权归作者所有。请勿转载和采集!