到了堆栈这里一下子就轻松了,算是一种暂时的解脱吧。经过了链表部分的学习和思考,我突然意识到严蔚敏教材的严谨性。下面是按照教材实现的堆栈操作代码,唯一有些疑问的是在Pop操作中要不要根据需要缩减堆栈的尺寸呢?
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define STACK_INIT_SIZE 100
#define STAK_INCREASEMENT 10
typedef int Status;
typedef int SElemType;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
Status InitStack(SqStack &S);
Status DestroyStack(SqStack &S);
Status ClearStack(SqStack &S);
Status StackEmpty(SqStack S);
int StackLength(SqStack S);
Status GetTop(SqStack &S, SElemType &e);
Status Push(SqStack &S, SElemType e);
Status Pop(SqStack &S, SElemType &e);
int main(void)
{
SqStack S;
InitStack(S);
// Push(S,2);
int i,j;
for(i = 0; i<190; i++)
{
Push(S,i);
}
for(i=0; i<17; i++)
{
Pop(S,j);
printf("%d\t",j);
}
system("pause");
}
Status InitStack(SqStack &S)
{
S.base = (SElemType *)malloc( STACK_INIT_SIZE * sizeof(SElemType) );
if(!S.base)
return ERROR;
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return OK;
}
Status DestroyStack(SqStack &S)
{
S.top = S.base;
free(S.base);
S.stacksize = 0;
return OK;
}
Status ClearStack(SqStack &S)
{
S.top = S.base;
S.base = (SElemType *)realloc(S.base, STACK_INIT_SIZE * sizeof(SElemType) );
S.stacksize = 100;
return OK;
}
Status StackEmpty(SqStack S)
{
if( S.base == S.top )
return TRUE;
return FALSE;
}
Status GetTop(SqStack &S, SElemType &e)
{
if( S.base == S.top )
return ERROR;
e = *(S.top - 1); // 这里一定要注意
return OK;
}
Status Push(SqStack &S, SElemType e)
{
if( (S.top - S.base) >= S.stacksize )
{
S.base = (SElemType *)realloc(S.base, ( S.stacksize + STAK_INCREASEMENT ) * sizeof(SElemType));
S.stacksize += STAK_INCREASEMENT;
if(!S.base)
return ERROR;
}
*S.top = e;
S.top++;
return OK;
}
Status Pop(SqStack &S, SElemType &e)
{
if(S.base == S.top)
return ERROR;
S.top--;
e = *S.top;
return OK;
}
感谢下方留言的朋友指出我的错误。