相关定义
- 栈和队列是操作受限的线性表,称为限定性数据结构
- 栈:仅限在表尾进行插入和删除的线性表
特点:后进后出(类似排队)
栈顶:表尾元素,出栈时从栈顶出
栈底:表头元素,入栈时从栈底入
- stackSize:当前栈可使用的最大容量(以elemtype个数为单位)
base:栈底指针,当base=NULL时表示栈结构不存在
top:栈顶指针,初始化时base=top,表明为空栈
又因为入栈时top+1,出栈时top-1,因此top始终指向栈顶元素的下一个位置,而base指向栈底元素
顺序栈的表示与相关操作实现
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
//一定要注意预定义与引入头文件后边均无分号,开始就因为加了;一直查不出错误来
typedef struct{
ElemType *base;
ElemType *top;
int stackSize;
}Stack;
Status InitStack(Stack *S);
ElemType GetStackTop(Stack S, ElemType *e);
Status Push(Stack *S, ElemType e);
Status Pop(Stack *S, ElemType *e);
int StackLength(Stack S, int *length);
Status ClearStack(Stack *S);
Status DestroyStack(Stack *S);
Status TraverseStack(Stack S);
Status InitStack(Stack *S){
S->base=(ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if(!S->base){
return OVERFLOW;
}
S->top=S->base;
S->stackSize=STACK_INIT_SIZE;
return OK;
}
ElemType GetStackTop(Stack S,ElemType *e){
if(S.base==S.top){
return ERROR;
}
*e=*(S.top-1);
return *e;
}
Status Push(Stack *S,ElemType e){
if(S->top-S->base>=S->stackSize){
S->base=(ElemType*)realloc(S->base,(S->stackSize+STACKINCREMENT)*sizeof(ElemType));
if(!S->base){
return OVERFLOW;
}
S->top=S->base+S->stackSize;//在栈空间不够的时候分配空间后,需要更新栈顶指针
S->stackSize+=STACKINCREMENT;
}//检查栈储存空间是否足够
*S->top=e;
S->top++;
return OK;
}
Status Pop(Stack *S,ElemType *e){
if(S->top==S->base){
return ERROR;
}
*e=*(S->top-1);
S->top--;
return OK;
}
int StackLength(Stack S, int *length){
int count=0;
while(S.top!=S.base){
S.top--;
count++;
}
*length=count;
return *length;
}
Status ClearStack(Stack *S){
if(S->top!=S->base){
S->top=S->base;
}
return OK;
}
Status DestroyStack(Stack *S){
free(S->base);
S->base=NULL;
free(S);
return OK;
}
Status TraverseStack(Stack S){
int count=1;
while(S.base!=S.top){
printf("The %dth elem is %d\n",count,*(S.top-1));
count++;
S.top--;
}
return OK;
}
关注公众号,让我们携手共进
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。