栈、初始、建立空栈、进栈、出栈
本帖最后由 奥普瓯江 于 2021-10-26 15:07 编辑原理:
代码:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef int Elemtype;
//建立一个类
typedef struct
{
Elemtype *base; //站底
Elemtype *top; //站顶
int stackSize; //当前可使用最大容量
}sqStack;
void InitStack(sqStack **E); //初始化创建一个站
void PopStack(sqStack *E, Elemtype n); //进栈
Elemtype PushStack(sqStack *E); //出栈
void PutStack(sqStack *E); //打印站内数据
Elemtype PushStack(sqStack *E) //出栈
{
Elemtype temp;
temp = *(E->top);
E->top--;
E->stackSize++;
return temp;
}
void PutStack(sqStack *E) //打印站内数据
{
Elemtype *temp = E->base;
while(temp != E->top)
//for(int i = 0; i < 10; i++)
{
printf("<%d>", *temp);
temp++;
}
printf("%d", E->stackSize);
putchar('\n');
}
void PopStack(sqStack *E, Elemtype n) //进栈
{
if(E->top - E->base >= E->stackSize)
{
E->base = (Elemtype *)realloc(E->base, (E->stackSize + MAXSIZE) * sizeof(Elemtype )); //扩充空间
if(!E->base)
{
exit(0);
}
E->top = E->base + E->stackSize;
E->stackSize = E->stackSize + MAXSIZE;
}
*(E->top) = n;
E->top++;
E->stackSize--;
}
void InitStack(sqStack **E)//初始化创建一个站
{
(*E)->base = (Elemtype *)malloc(MAXSIZE * sizeof(Elemtype )); //创建一个MAXSIZE的空间把开始地址传给E->base
if(!(*E)->base) //如果空间分配失败E->base == NULL,那么就执行以下程序
{
exit (0);
}
(*E)->top = (*E)->base; //让两个指针相等
(*E)->stackSize = MAXSIZE; //把可储存空间传给节点
}
int main()
{
sqStack *T;
InitStack(&T);//建立站
for(int i = 0 ; i < 20; i++)
{
PopStack(T, i);
}
PutStack(T);
for(int i = 0 ; i < 20; i++)
{
PushStack(T);
PutStack(T);
}
return 0;
页:
[1]