#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define StackSize 100 // 栈所能容纳的最大元素个数
typedef int DataType;
typedef struct node
{
DataType data[StackSize]; // 存储元素的数组
int top; // 栈顶指针
}SqStack;
bool Init_Stack(SqStack * S); // 对栈进行初始化
bool Clear_Stack(SqStack * S); // 清空栈 (栈的数组内存是静态分配的,无需销毁)
bool Push_Stack(SqStack * S, DataType x); // 压栈
bool Pop_Stack(SqStack * S, DataType * x);// 出栈
int GetTop_Stack(SqStack * S); // 取栈顶元素
bool Empty_Stack(SqStack * S); // 判栈空
bool Traverse_Stack(SqStack * S); // 遍历栈
bool Full_Stack(SqStack * S); // 判栈满
int Length_Stack(SqStack * S); // 栈长度
int main()
{
int i,n,val;
DataType x;
SqStack S;
if(Init_Stack(&S))
printf("初始栈成功!\n");
else
printf("初始栈失败!\n");
printf("输入入栈元素个数:");
scanf("%d",&n);
for(i=0; i<n; ++i)
{
printf("第%d个元素:",i+1);
scanf("%d",&val);
Push_Stack(&S,val);
}
printf("遍历栈:");
Traverse_Stack(&S);
printf("栈顶元素:%d\n\n",GetTop_Stack(&S));
printf("栈的元素个数:%d\n\n", Length_Stack(&S));
if(Pop_Stack(&S, &x))
{
printf("出栈成功!\n");
printf("出栈元素:%d\n",x);
}
else
printf("出栈失败!\n");
printf("遍历栈:");
Traverse_Stack(&S);
if(Clear_Stack(&S))
printf("清空成功!\n");
else
printf("清空失败!\n");
printf("遍历栈:");
Traverse_Stack(&S);
return 0;
}
bool Init_Stack(SqStack * S)
{
S->top = -1; // 从下标0开始存储元素
return true;
}
bool Clear_Stack(SqStack * S)
{
S->top = -1;
return true;
}
bool Push_Stack(SqStack * S, DataType x)
{
if(Full_Stack(S))
return false;
S->data[++S->top] = x;
return true;
}
bool Pop_Stack(SqStack * S, DataType * x)
{
if(Empty_Stack(S))
return false;
*x = S->data[S->top--];
return true;
}
int GetTop_Stack(SqStack * S)
{
return S->data[S->top];
}
int Length_Stack(SqStack * S)
{
int cnt = 0;
int i = S->top;
while(i!=-1)
{
cnt++;
i--;
}
return cnt;
}
bool Empty_Stack(SqStack * S)
{
if(S->top==-1)
return true;
else
return false;
}
bool Traverse_Stack(SqStack * S)
{
if(Empty_Stack(S))
return false;
int i = S->top;
while(i!=-1)
{
printf("%3d",S->data[i--]);
}
printf("\n\n");
return true;
}
bool Full_Stack(SqStack * S)
{
if(S->top==StackSize-1)
return true;
else
return false;
}
顺序栈(C语言实现)
猜你喜欢
转载自blog.csdn.net/Mr_Morgans/article/details/121003028
今日推荐
周排行