#include <stdio.h> #include <stdlib.h> //提供malloc()原型 #include <stdbool.h> //提供true false原型 #define MaxSize 10 #define ERROR -1 typedef struct SNode *Stack; typedef int ElementType ; struct SNode { ElementType *Data; //数组存放数据 int Top; //top指明栈顶的位置 int Maxsize; //堆栈最大容量 }; Stack CreateStack(int Max) { Stack S = (Stack)malloc(sizeof(struct SNode)); S->Data = (ElementType *)malloc(Max * sizeof(ElementType)); S->Top = -1; S->Maxsize = Max; return S; } bool Push(Stack PtrS,ElementType item) { if(PtrS->Top==MaxSize-1) //判断数组是否已满 { printf("堆栈已满!"); return false; } else { PtrS->Data[++(PtrS->Top)] = item; //添加元素并更新top return true; } } ElementType Pop(Stack PtrS) { if(PtrS->Top == -1) { printf("堆栈空"); //判断数组是否已空 return ERROR; } else { return (PtrS->Data[(PtrS->Top)--]); //返回值并更新top } } int main() { Stack Ptr; int Tmp; Ptr=CreateStack(10); //初始化栈 Push(Ptr,10); //在数组0的位置Push 数值10 Tmp = Pop(Ptr); // 取出栈的最上面的值赋给变量Tmp printf("%d",Tmp); return 0; }
原文:https://www.cnblogs.com/flashBoxer/p/9404564.html