C语言实现堆栈(自己的)
stack.h
#ifndef __STACK_H__ #define __STACK_H__ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> typedef int ElementType; struct SNode { ElementType *Data; /* 存储元素的数组 */ int Top; /* 栈顶指针 */ int MaxSize; /* 堆栈最大容量 */ }; typedef struct SNode *Stack; Stack CreateStack( int MaxSize ); //建立结构体堆栈 bool IsFull( Stack S ); //判断堆栈是是否溢出 bool Push( Stack S, ElementType X ); //压栈 bool IsEmpty( Stack S ); //判断堆栈是是否为空 ElementType Pop( Stack S ); //出栈 #endif
stack.c
#include "stack.h" #include "sys.h" u8 Choose_Stack_Flag=0; //未检测到加减符号时候,0:一个结构体,检测到1:另一个结构体 Stack CreateStack( int MaxSize ) { Stack S = (Stack)malloc(sizeof(struct SNode)); S->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType)); S->Top = -1; S->MaxSize = MaxSize; return S; } bool IsFull( Stack S ) { return (S->Top == S->MaxSize-1); } bool Push( Stack S, ElementType X ) { if ( IsFull(S) ) { printf("堆栈满"); return false; } else { S->Data[++(S->Top)] = X; return true; } } bool IsEmpty( Stack S ) { return (S->Top == -1); } ElementType Pop( Stack S ) { if ( IsEmpty(S) ) { printf("堆栈空"); return ERROR; /* ERROR是ElementType的特殊值,标志错误 ERROR 0 */ } else return ( S->Data[(S->Top)--] ); }