栈的定义:
仅限在表尾进行插入和删除操作的线性表
注意事项:
- 设栈S = (a1,a2,a3,a4,a5),则a1为栈底,a2为栈顶;
- 操作原则:后进先出(Last In First Out,LIFO)
栈的基本操作:(&为引用类型)
- InitStack(&S) 构建一个空栈S
- DestroyStack(&S) 销毁栈
- ClearStack(&S) 清空栈
- StackEmpty(S) 若栈为空返回true,否则返回false
- StackLength(S) 返回栈的长度
- GetTop(S) 返回栈顶元素(栈非空)
- Push(&S , e) 插入元素e作为新的栈顶元素
- Pop(&S , e) 删除栈顶元素,并用e返回其值
- StackTraverse(S) 从栈底到栈顶依次对每个数据进行访问
栈的两种存储表示方式
- 顺序栈
- 链栈
顺序栈的表示和实现(一个完整的例子)
思想:栈顶指针 S.top ,初始设置 S.top = -1;栈顶元素 S.data[S.top]
进栈操作:栈不满时,栈顶指针先加1,再送值到栈顶
出栈操作:栈非空时,先取栈顶元素,再 S.top–
栈空条件:S.top == -1
栈满条件:S.top == MaxSize-1
栈长:S.top + 1
#include<bits/stdc++.h>
using namespace std;
//顺序栈的表示和实现
#define MAXSIZE 100 //分配的存储空间
typedef int ElemType;
typedef int Statue;
typedef struct {
ElemType data[MAXSIZE] ;//存放栈中元素
int top; //栈顶指针
} SqStack;
void InitStack(SqStack &S); //初始化
bool StackEmpty(SqStack S);//判断栈是否空
bool Push(SqStack &S,ElemType x);//进栈
bool Pop(SqStack &S,ElemType &e);//出栈
bool GetTop(SqStack S, ElemType &e);//读栈顶元素
Statue StackLength(SqStack S);//获取栈的长度
void Print_s(SqStack S);//遍历栈
int main() {
SqStack s;
InitStack(s);
Push(s,5);
Push(s,1);
Push(s,8);
Print_s( s);
int e;
Pop(s,e);
cout<<"出栈"<<e<<endl;
Print_s(s);
cout<<StackEmpty(s)<<endl;
}
void Print_s(SqStack S) {
while(S.top!=-1) {
cout<<S.data[S.top--];
}
cout<<endl;
}
Statue StackLength(SqStack S) {
return ++S.top;
}
bool GetTop(SqStack S, ElemType &e) {
//读栈顶元素
if(S.top==-1)
return false;
e = S.data[S.top];
return true;
}
bool Pop(SqStack &S,ElemType &e) {
//出栈
if(S.top==-1)
return false;//栈空报错
e=S.data[S.top--];//先出栈,指针再减1
return true;
}
bool Push(SqStack &S,ElemType x) {
//进栈
if(S.top==MAXSIZE-1) //栈满
return false;
S.data[++S.top]=x; //等价于 S.top=S.top+1;S.data[S.top]=x
return true;
}
bool StackEmpty(SqStack S) {
//判断是否为空
if(S.top==-1)
return true;
else
return false;
}
void InitStack(SqStack &S) {
//初始化
S.top = -1 ;//初始化栈顶指针
}
链栈
//存储结构
typedef struct Linknode{
ElemType data; //数据域
struct Linknode *next; //指针域
}*LinkStack,StackNode;
//链栈入栈,相当于链表的头插法
Status Push(LinkStack &s,SElemType e){
p = new StackNode; //生成一个新节点
p->data = e;
p->next=s;
s=p;
return ok;
}
//链栈的出栈
Status Pop(LinkStack &s,SElemType &e){
//删除栈顶元素,用e返回其值
if(s==null) return error; //栈空
e=s->data;
p=s;
s=s->next;
delete p;
return ok;
}
共享栈
利用栈底位置相对不变的特性,可让两个顺序栈共享一个一维数组空间,将两个栈的栈底分别设置在共享空间的两端,两个栈顶向共享空间的中间延伸。
两个栈的栈顶指针都指向栈顶元素,top0=-1时,0号栈为空,top1=Maxsize时1号栈为空
仅当两个栈顶指针相邻(top0+top1==1)时,栈满。