c棧的基操
阿新 • • 發佈:2021-12-11
先放程式碼
點選檢視程式碼
#include <stdio.h> #define Maxsize 50 #define true 1 #define false 0 typedef int Elemtype; typedef struct{ Elemtype data[Maxsize]; int top; }SqStack; //初始化 void InitStack(SqStack *S){ S->top = -1; } //判空 int StackEmpty(SqStack S){ if(S.top==-1) return true; else return false; } //進棧or壓棧 int Push(SqStack *S,Elemtype x){ if(S->top==Maxsize-1) //棧滿,報錯 return false; S->data[++S->top]=x; //指標先加1,再入棧 return true; } //出棧or彈棧 int Pop(SqStack *S,Elemtype x){ if(S->top==-1) //棧空,報錯 return false; x=S->data[S->top--]; //先出棧,指標再減一 return x; } //讀棧頂元素 int GetTop(SqStack S,Elemtype x){ if(S.top==-1) //棧空,報錯 return false; x=S.data[S.top]; return x; } void S_p(SqStack S){ while(S.top>-1) printf("%d ",S.data[S.top--]); } int main() { SqStack S; InitStack(&S); Push(&S,0);Push(&S,1);Push(&S,2);S_p(S); return 0; }