69,382
社区成员
发帖
与我相关
我的任务
分享
/***********************************************************************
*
***********************************************************************/
#include <stdio.h>
#include <stdlib.h>
struct SequentialStack
{
int* date; /*数据域*/
int top; /*date[top]指向栈顶元素,栈为空时,top=-1*/
int stacksize; /*栈空间的大小*/
};
typedef struct SequentialStack SqStack;
typedef SqStack* SSp;
/***********************************************************************
*0.错误函数
***********************************************************************/
void Error(char* s)
{
printf("%s\n",s);
}
/***********************************************************************
*1.初始化栈
***********************************************************************/
void InitSequentialStack(SSp p,int n)
{
p->date=(int*)malloc(n*sizeof(int));
p->top=-1;
p->stacksize=n;
}
/***********************************************************************
*2.销毁栈
***********************************************************************/
void DestroySequentialStack(SSp p)
{
p->top=-1;
p->stacksize=0;
free(p->date);
}
/***********************************************************************
*3.求栈长
***********************************************************************/
int LengthSequentialStack(SSp p)
{
return p->top + 1;
}
/***********************************************************************
*4.取栈顶元素
***********************************************************************/
int GetTopLengthSequentialStack(SSp p)
{
if(p->top != -1)
{
return p->date[p->top];
}
else
{
Error("Stack Empty!");
return 0;
}
}
/***********************************************************************
*5.入栈
***********************************************************************/
void PushSequentialStack(SSp p,int x)
{
if((p->top + 1) >= (p->stacksize))
{
Error("Stack Overflow!");
}
else
{
p->top = p->top + 1;
p->date[p->top] = x;
}
}
/***********************************************************************
*6.出栈
***********************************************************************/
int PopSequentialStack(SSp p)
{
if((p->top) >= 0)
{
int x = p->date[p->top];
p->top = p->top - 1;
return x;
}
else
{
Error("Stack Empty!");
return 0;
}
}
/***********************************************************************
*7.依次弹出栈中所有元素
***********************************************************************/
void PrintPopSequentialStack(SSp p)
{
int i = p->top;
printf("栈内元素如下:");
while(i >= 0)
{
printf("%d ",p->date[i]);
i = i -1;
}
printf("\n输出完毕\n\n");
}