栈:只允许在一端进行插入或删除的线性表。
栈顶:栈中允许插入和删除的一端。
栈底:固定的,不允许进行插入和删除的另一端。
栈的特点:
1.栈是受限的线性表,具有线性关系。
2.先进后出(FILO)
顺序栈的定义
#define MAXSIZE 50 //定义栈中元素的最大个数
typedef struct{
ElemType data[MAXSIZE]; //存放栈中元素
int top; //栈顶指针
}SqStack;
空栈的判定条件通常定为top=-1,满栈的判定条件通常为top==MAXSIZE-1,栈中数据元素个数为top+1。
顺序栈的操作:
1.判空
bool StackEmpty(SqStack S){
if(s.top==-1) return false;
else return true;
}
2.进栈
bool Push(Sqstack &s,ElemType x){
if(s.top==MAXSIZE-1) return false;
s.data[++top]=x;
return true;
}
3.出栈
bool Pop(SqStack &s, ElemType &x){
if(s.top==-1) return false;
x=s.data[s.top--];
return true;
}
4.读取栈顶元素
bool GetTop(SqStack s,ElemType &x){
if(s.top==-1) return false;
x=s.data[s.top];
return true;
}
顺序栈的问题:顺序栈的存储空间大小需要事先开辟好,很多时候对每个栈各自开辟的存储空间的利用率不如将各个栈的存储空间共享
共享栈的定义:
#define MAXSIZE 100 //定义栈中元素的最大个数
typedef struct{
ElemType data[MAXSIZE]; //存放栈中元素
int top1; //栈1栈顶指针
int top2; //栈2栈顶指针
}SqDoubleStack;
共享栈的进栈操作:
bool Push(SqDoubleStack &S,ElemType x,int StackNum){
if(S.top1+1==S.top2) return false; //栈满
if(StackNum==1) S.data[++top1]=x; //栈1有元素进栈
else if(StackNum==2) S.data[--top2]=x; //栈2有元素进栈
return true;
}
链式栈:
栈的链式存储结构也叫作链栈。
链栈的定义:
typedef struct SNode{
ElemType data; //数据域;
struct SNode *next; //指针域;
}SNode, *SLink;
typedef struct LinkStack{
SLink top; //栈顶指针
int count; //链栈结点书
}LinkStack;
空栈的判定条件通常定为top==NULL;
链栈的操作
1.入栈:
bool Push(LinkStack *s,ElemType x){
SLink p=(SLink)malloc(sizeof(SNode)); //分配空间
p->data=x;
p->next=s->top;
s->top=p;
s->count++;
return true;
}
2.出栈
bool Pop(LinkStack *s,ElemType &x){
if(s->top==NULL) return false;
x=s->top->data;
SLink p=s->top;
s->top=s->top->next;
free(p);
s->count--;
return true;
}