From 64672d81ffd8c0e32564d091e79fadfd1548b1ea Mon Sep 17 00:00:00 2001 From: ViolentAyang <76544389+ViolentAyang@users.noreply.github.com> Date: Sat, 19 Mar 2022 21:42:02 +0800 Subject: [PATCH] =?UTF-8?q?Create=20=E8=8E=B7=E5=8F=96=E6=A0=88=E9=A1=B6?= =?UTF-8?q?=E5=85=83=E7=B4=A0.c?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 栈/获取栈顶元素.c | 63 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 栈/获取栈顶元素.c diff --git a/栈/获取栈顶元素.c b/栈/获取栈顶元素.c new file mode 100644 index 0000000..966cfbf --- /dev/null +++ b/栈/获取栈顶元素.c @@ -0,0 +1,63 @@ +#include +#include +#include +#define MaxSize 10 + +typedef struct{ + int data[MaxSize]; //静态数组存放栈中元素 + int top; //栈顶指针 +}SqStack; + +//初始化栈 +void InitStack(SqStack *S){ + S->top = -1; +} +//新元素进栈 +bool Push(SqStack *S,int x){ + if(S->top==MaxSize-1){ + return false; + } + S->top += 1; + S->data[S->top] = x; + return true; +} +//出栈操作 +int Pop(SqStack *S,int x){ + if(S->top==-1){ + return false; + } + x = S->data[S->top]; + S->top -= 1; + return x; +} +//读取栈顶元素操作 +bool getTop(SqStack *S,int *x){ + if(S->top==-1){ + return false; + } + *x = S->data[S->top]; + S->top -= 1; + return true; +} +//打印 +void PrintStack(SqStack S){ + if(S.top==-1){ + printf("栈为空!"); + } + for(int i=0;i<=S.top;i++){ + printf("%d\n",S.data[i]); + } +} +int main(){ + SqStack S; + int x = -1; + InitStack(&S); + Push(&S,1); + Push(&S,2); + Push(&S,3); + Push(&S,4); + Push(&S,5); + getTop(&S,&x); + printf("栈顶元素为:%d",x); + return 0; +}