一、概念
栈是限定仅在表尾进行插入或删除操作的线性表。表尾端称为栈顶,表头端成为栈底,栈的一大特点是先进后出。
二、顺序栈的实现
和线性表一样,栈也有两种存储方式,这里实现顺序栈。
1.栈结构
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}
2.具体实现
(1)栈空:s.top == s.base;
(2)栈满:s.top - s.base = stacksize;
(3)入栈和出栈规则:入栈时,赋值后top指针才上移,栈顶指针始终在栈顶元素的下一个位置上;出栈时,指针下移后在取值。
//头文件
#pragma once
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREASEMENT 10
typedef int SElemType;
typedef struct{
SElemType *base;
SElemType *top;
int stackSize;
}SqStack;
bool initStack(SqStack &s);
bool destoryStack(SqStack &s);
bool clearStack(SqStack &s);
bool stackEmpty(SqStack s);
int stackLength(SqStack s);
bool getTop(SqStack s,SElemType &e);
bool push(SqStack &s,SElemType e);
bool pop(SqStack &s,SElemType &e);
bool stackTraverse(SqStack s);
//cpp文件
#include"stack.h"
bool initStack(SqStack &s){
s.base = (SElemType*)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!s.base) return false;
s.top = s.base;
s.stackSize = STACK_INIT_SIZE;
return true;
}
bool destoryStack(SqStack &s){
if(!s.base) return false;
s.stackSize = 0;
free(s.base);
s.top = s.base = NULL;
return true;
}
bool clearStack(SqStack &s){
if(s.base == s.top) return false;
s.top = s.base;
return true;
}
bool stackEmpty(SqStack s){
if(s.base == s.top)
return true;
return false;
}
int stackLength(SqStack s){
return s.top - s.base;
}
bool getTop(SqStack s,SElemType &e){
if(s.base == s.top){
e = 0 ;
return false;
}
e = *(s.top - 1);
return true;
}
bool push(SqStack &s,SElemType e){
if((s.top - s.base) >= s.stackSize){
s.base = (SElemType*)realloc(s.base,(s.stackSize + STACKINCREASEMENT) * sizeof(SElemType));
if(!s.base) return false;
s.top = s.base + s.stackSize;
s.stackSize = s.stackSize + STACKINCREASEMENT;
}
*s.top++ = e;//先入栈,再上移动,
return true;
}
bool pop(SqStack &s,SElemType &e){
if(s.base == s.top) return false;
e = *(--s.top);//先向下移动,在出栈
return true;
}
bool stackTraverse(SqStack s){
if(s.top == s.base) return false;
SElemType *p = s.top - 1;
while((p - s.base) >= 0){
printf("%d ",*p);
p--;
}
return true;
}
int main(){
SqStack s;
initStack(s);
push(s,1);
push(s,2);
push(s,3);
stackTraverse(s);
printf("\n");
printf("length = %d\n",stackLength(s));
SElemType e ;
getTop(s,e);
printf("top = %d\n",e);
pop(s,e);
stackTraverse(s);
printf("\n");
getchar();
return 0;
}