本节导图:
栈的定义
栈是限定仅在表尾进行插入或删除操作的线性表
特点:先进后出
- 栈图示:
写在程序前面
include<iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int ElemType;// 线性表中元素的类型
#define MAXSIZE 100//顺序栈存储空间的初始分配量
顺序栈的操作:
顺序栈的存储结构
typedef struct {
ElemType* base;//栈顶指针
ElemType* top;//栈底指针
int stacksize;//栈的容量
}SqStack;
初始化
Status InitStack(SqStack &S) //传递的是栈,构造一个空栈{
S.base = new ElemType[MAXSIZE];//为顺序栈分配一个最大容量为MAXSIZE的数组空间
if (!S.base) {
return ERROR;//申请失败,报错
}
S.top = S.base;//top 初始化为base 空栈
S.stacksize = MAXSIZE;//栈的容量置为最大容量MAXSIZE 100
return OK;
}
入栈的概念:相当于顺序表只能在表尾插入元素
出栈的概念:相当于顺序表只能在表尾删除元素
入栈代码
步骤:
1、判断栈满?S.top - S.base == S.stacksize
2、top++、*S.top++=e
- 入栈图示:
Status Push(SqStack& S, ElemType e) {
if (S.top - S.base == S.stacksize) {//top-base=size判断栈满头-底部=容量
return ERROR;
}
*S.top++ = e; //分解:*S.top=e(指针的内容)、top++(往上移动);
return OK;
}
出栈代码
步骤:
1、判断栈空?S.top==S.base
2、- -S.top,e=*- -S.top
- 出栈图示:
//出栈
Status Pop(SqStack &S, ElemType& e)//要改变传递的e,用引用
{
if (S.top == S.base) {//判断栈空?报错
return ERROR;
}
e = *--S.top;//分解:--top,e=*S.top
return OK;
}
查看栈顶元素代码
步骤:
1、步骤:判断栈空?
2、top-1,*(S.top-1)
- 查看栈顶元素图示:
// 查看栈顶元素
ElemType GetTop(SqStack S) {//调用时只需要传一个栈进来
if (S.top != S.base) {//判断栈空,报错
return*(S.top - 1);//不是top--,因为只是查看top指针的前一个指针所指向的元素
}else return ERROR;
}
主函数
int main(int argc, const char* argv[]) {
SqStack S;//创建栈
InitStack(S);//初始化
//入栈
ElemType e = 100;
Push(S, e);
e = 102;
Push(S, e);
//出栈
ElemType e2,e3;
Pop(S, e2);//出栈只能一个一个元素出出完e2出e3
Pop(S, e3);
cout <<e2 << " "<<e3<<" " << endl;
cout << GetTop(S) << endl;
}
源程序
#include <iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int Status;
typedef int ElemType;// 线性表中元素的类型
#define MAXSIZE 100//顺序栈存储空间的初始分配量
typedef struct {
ElemType* base;//顶
ElemType* top;//底
int stacksize;//容量
}SqStack;
//初始化
Status InitStack(SqStack &S) {//构造一个空栈
S.base = new ElemType[MAXSIZE];//为顺序栈分配一个最大容量为MAXSIZE的数组空间
if (!S.base) {
return ERROR;//申请失败
}
S.top = S.base;
S.stacksize = MAXSIZE;//栈的容量
return OK;
}
//入栈
Status Push(SqStack& S, ElemType e) {
if (S.top - S.base == S.stacksize) {//top-base=size判断栈满头-底部=容量
return ERROR;
}
*S.top++ = e; //*S.top=e、top++;
return OK;
}
//出栈
Status Pop(SqStack &S, ElemType& e)//引用
{
if (S.top == S.base) {
return ERROR;
}
e = *--S.top;//--top,e=*top
return OK;
}
// 查看栈顶元素
ElemType GetTop(SqStack S) {//调用时只需要传一个栈进来
if (S.top != S.base) {
return*(S.top - 1);//返回栈顶元素的
}else return ERROR;
}
int main(int argc, const char* argv[]) {
SqStack S;//创建栈
InitStack(S);//初始化
//入栈
ElemType e = 100;
Push(S, e);
e = 102;
Push(S, e);
//出栈
ElemType e2,e3;
Pop(S, e2);//出栈只能一个一个元素出出完e2出e3
Pop(S, e3);
cout <<e2 << " "<<e3<<" " << endl;
cout << GetTop(S) << endl;
}