/*栈:
**也可以看作线性表,其特殊行在于
**栈是线性表操作的子集,是操作受限的线性表
**因此,可称为限定性的数据结构
**一般来说,在初始化设空栈时不应该限定栈的最大容量
**先为栈分配一个基本容量,不够用时再逐段扩大
**当 base = NULL 时,表明栈结构不存在
** base = top 时,表明栈空
*/
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define INFEASIBLE -2
#define INIT_STACK_SIZE 100
#define INCREAMENTSTACK 10
typedef int SElemType;
typedef int Status;
typedef struct{
SElemType *top;
SElemType *base;
int stacksize;
}SqStack;
//构造一个空栈
Status InitStack( SqStack &S ){
S.base = S.top = (SElemType*) malloc (sizeof(SElemType));
if( !S.top )
return ERROR;
S.stacksize = INIT_STACK_SIZE;
return OK;
}
// 把 S 设置为空栈
Status ClearStack( SqStack &S ){
SElemType *p, *q;
q = p = S.top - 1;
while( S.top != S.base ){
q = p - 1;
free(p);
p = q;
S.top--;
}
free(q);
return OK;
}
//销毁 S
Status DestroyStack( SqStack &S ){
ClearStack(S);
free(S.top);
free(S.base);
return OK;
}
//若栈 S 为空栈,则返回TRUE, 否则返回 FALSE
Status StackEmpty( SqStack S ){
if( S.top == S.base )
return TRUE;
else
return FALSE;
}
//返回 S 的元素个数,即栈的长度
int StackLength( SqStack S ){
return ( S.top - S.base );
}
//若栈不空,则用 e 返回 S 的栈顶元素,并返回 OK, 否则返回ERROR
Status GetTop( SqStack S, SElemType &e ){
if( S.top != S.base ){
e = *(S.top - 1);
return OK;
}
else
return ERROR;
}
//若栈不空,则删除 S 的栈顶元素,用 e 返回其值,并返回 OK;否则返回 ERROR
Status Pop( SqStack &S, SElemType &e ){
if( StackLength(S) ){
e = *(S.top - 1);
*--S.top;
return OK;
}
else
return ERROR;
}
//插入元素 e 为新的栈顶元素
Status Push( SqStack &S, SElemType e ){
if( StackLength(S) >= S.stacksize ){
S.base = (SElemType*) realloc (S.base,INCREAMENTSTACK * sizeof(SElemType));
S.stacksize += INCREAMENTSTACK;
}
*S.top = e;
S.top++;
return OK;
}
顺序栈的实现
#include <stdio.h>
#include "Stack.h"
int main(void)
{
SqStack S;
//Initilize a empty Stack
InitStack( S );
printf("top = %u, base = %u, stacksize = %d\n",
S.top, S.base, S.stacksize);
//Push 5 elements into S
for( int i = 0; i < 5; ++i ){
Push(S,i);
printf("%d ",*(S.top - 1));
}
putchar('\n');
//return length of Stack S
printf("S.length = %d\n",StackLength(S));
//Get the top element from S
SElemType get_e;
GetTop(S,get_e);
printf("The top element is %d\n",get_e);
//Pop the top element
SElemType pop_e;
Pop(S,pop_e);
printf("Pop element is %d\n",pop_e);
//Check the S
for( int i = 0; i < StackLength(S); ++i ){
printf("%d ",*(S.top - 1 - i));
}
return 0;
}
哎呀。。。最近懒了好多,要好好反省一下。