数据结构中的栈(c)
📅 2026/8/1 12:07:37
👁️ 阅读次数
📝 编程学习
栈中的初始化和进栈操作
#define_CRT_SECURE_NO_WARNINGS#include<stdio.h>#defineMaxSize10//栈中元素的最大个数typedefstruct{intdata[MaxSize];//静态数组存放栈中元素inttop;//栈顶指针}SqStack;//Sequence - 顺序//初始化栈voidInitStack(SqStack&S){S.top=-1;//初始化栈顶指针}//判断栈空boolStackEmpty(SqStack S){if(S.top==-1){printf("Now the Stack is empty!\n");returntrue;}else{returnfalse;}}//进栈操作boolPush(SqStack&S,intx){if(S.top==MaxSize-1)returnfalse;S.top+=1;//等价于S.data[S.top]=x;//S.data[++S.top] = x;returntrue;}//出栈操作boolPop(SqStack&S,int&x){if(S.top==-1)returnfalse;x=S.data[S.top--];returntrue;}voidtestStack(){SqStack S;//声明一个顺序栈(分配空间)InitStack(S);StackEmpty(S);Push(S,3);printf("SqStack: %d\n",S.data[0]);Push(S,5);printf("SqStack: %d %d\n",S.data[0],S.data[1]);Push(S,7);printf("SqStack: ");for(inti=0;i<=S.top;++i){printf("%d ",S.data[i]);}printf("\n----------------");}intmain(){testStack();return0;}
编程学习
技术分享
实战经验