C语言实现堆栈功能
本程序实现堆栈的初始化、入栈、出栈、判断栈空、查看栈顶元素、销毁功能。
stack.h文件
#ifndef __STACK_H__ #define __STACK_H__ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define SIZE_stack 1024 typedef int datatype; struct stack { datatype data[SIZE_stack]; int top; }; struct stack *InitStack(void); bool IsEmptyStack(struct stack *s); void PushStack(struct stack *s, datatype data); datatype PopStack(struct stack *s); datatype TopStack(struct stack *s); void DestroyStack(struct stack *s); #endif /* __STACK_H__ */
stack.c文件
#include "stack.h" struct stack *InitStack(void) { struct stack *s; s = (struct stack *)malloc(sizeof(struct stack)); if (s == NULL) exit(-1);//内存不足 s->top = 0; return s; } bool IsEmptyStack(struct stack *s) { return s->top == 0; } void PushStack(struct stack *s, datatype data) { if (s->top == SIZE_stack) exit(-2);//上溢 s->data[s->top++] = data; } datatype PopStack(struct stack *s) { if (s->top == 0) exit(-3);//下溢 return s->data[--s->top]; } datatype TopStack(struct stack *s) { if (s->top == 0) exit(-4);//栈空 return s->data[s->top - 1]; } void DestroyStack(struct stack *s) { free(s); }
原文地址:https://blog.csdn.net/liuzhaoze2000/article/details/102879755