栈是比较重要的数据结构(书上是这么说的,我还没看到后面去!),和队列一样,也是属于线性表的一种特例,存储方面也是存在顺序存储和链式存储,链式存储比较简单吧,实现起来应该不复杂,和单链表差不多,而且使用的栈一般都是顺序结构的!
其实,我认为既然是数组,那么在声明数据结构的时候,就应该有data[MAXSIZE]等,但是后来我发现,这样无法实现动态分配空间,所以使用了这种形式的声明
#include<stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
#define ERROR 0
#define OK 1
#define INCREASEMENT 10
//typedef后面木有分号,好伐?
typedef int ElemType;
typedef int Status;
typedef struct
{
ElemType *base;
ElemType *top;
int StackLength;
}SqStack;
Status InitStack(SqStack *S)
{
S->base = (ElemType *)malloc(MAXSIZE*(sizeof(ElemType)));
if (!S->base)
{
printf("No enough space");
exit(1);
}
S->top = S->base;
S->StackLength = MAXSIZE;
return OK;
}
Status Push(SqStack *S,ElemType e)
{
if (S->top - S->base >= S->StackLength)
{
S->base = (ElemType *)realloc(S->base,(MAXSIZE+INCREASEMENT)*sizeof(ElemType));
if (!S->base)
{
printf("No more space");
exit(1);
}
S->top = S->base+MAXSIZE;
S->StackLength += INCREASEMENT;
}
*(S->top) = e;
S->top++;
return OK;
}
//删除某个元素玩玩,LIFO!
Status Pop(SqStack *S,ElemType *e)
{
if (S->top == S->base)
{
printf("there is no element in the stack");
exit(1);
}
*e = *(--S->top);
return OK;
}
//删除整个栈
Status DestroyStack(SqStack S)
{
while (S.top != S.base)
{
free(--S.top);
}
return OK;
}
int main()
{
int i,j;
SqStack S;
ElemType e;
InitStack(&S);
for (i = 0;i<10;i++)
{
Push(&S,i);
}
for(j = 0;j <10;j++)
{
Pop(&S,&e);
printf("%d\n",e);
}
while(1);
}
其实对栈的销毁还是不太懂!对于分配了的空间,只需要释放指向数组的指针就可以了吗?
Status DestoryStack(SqStack &S)
{
free(S.base);
S.base = NULL;
S.top = NULL;
S.stacksize = 0;
return OK;
}
上面的实现,我觉得不妥,应该是从申请的空间中,逐次释放才可以!
Status DestroyStack(SqStack S)
{
int i,len;
len = S.StackLength;
for (i = 0;i<len;i++)
{
free(--S.top);
}
S.top =S.base = NULL;
S.StackLength = 0;
return OK;
}