顺序栈的基本操作,有个地方没搞懂,以后会来更新的。
//栈:只能通过对栈顶元素的操作来修改栈的一种特殊线性数据结构 FILO
#define SATCK_INIT_SIZE 100 //初始容量
#define STACKINCREMENT 10 //每次新增加容量
#include<stdio.h>
#include<stdlib.h>
typedef struct {
int * base;//栈底指针
int * top; //栈顶指针 //这里top始终指向栈底元素的下一个位置
int stack_size;
} Sqstack;
void Init_stack(Sqstack *); //初始化一个空栈
void Fill_stack(Sqstack *); //填充栈
void Print_stack(Sqstack *); //输出栈
void Delete_stack_top(Sqstack *); //删除栈顶元素
void Add_stack_top(int ,Sqstack *); //插入元素
void Judge_full(Sqstack *); //判断是否满栈,如若满栈增加分配内存
int main() //测试各个函数的功能
{
Sqstack * S;
int e=100;
S = (Sqstack *)malloc(sizeof(Sqstack));
// Sqstack p;
// S =& p;
//这里提供了另一种初始化指针的方法(dev平台,vs2017不支持),如若不初始化,程序将异常退出
Init_stack( S );
Fill_stack( S);
Print_stack(S);
Delete_stack_top(S);
Print_stack(S);
Add_stack_top(e,S);
Print_stack(S);
return 0;
}
void Init_stack(Sqstack * S )
{
S->base = (int *)malloc(SATCK_INIT_SIZE *sizeof(int ));
if(!S->base)
{
printf("Fail to build the stack");
exit(1);
}
S->top = S->base; //初始化栈底和栈顶为同一位置
S->stack_size = SATCK_INIT_SIZE; //栈的初始化容量
}
void Fill_stack(Sqstack *S)
{
int i;
for(i=0;i<9;i++)
{
Judge_full(S);
*S->top++ = i; //将i存入*S->top,即栈顶,并将栈顶指针后移
}
}
void Print_stack(Sqstack *S )
{
int * p;
p = S->top;
if(S->base ==S->top ) //相等意味着栈为空
{
printf("the stack is empty");
exit(3);
}
printf("the elements of the stack:\n");
while(p != S->base)
{
printf("%d ",*--p); //从栈顶输出直至栈底
}
printf("\n");
}
void Delete_stack_top(Sqstack *S)
{
if(S->base ==S->top )
{
printf("the stack is empty");
exit(3);
}
S->top--; //删除栈顶元素
}
void Judge_full(Sqstack *S)
{
if((S->top)-(S->base) >= S->stack_size)
//栈满 //数据结构书上是“>=”为什么不是“==”呢 ?什么情况会出现>=呢?
{
S->base = realloc(S->base,(S->stack_size + SATCK_INIT_SIZE)*sizeof(int )) ;
//增加分配内存
if(!S->base)
{
printf("the Stack is Full but Fail to Realloc");
exit(2);
}
S->top = S->base + S->stack_size; //这里对应“>=”注释
S->stack_size += SATCK_INIT_SIZE;
}
}
void Add_stack_top(int e,Sqstack *S)
{
Judge_full(S);
*S->top++ = e; //在栈顶存入e并将栈顶指针后移
}