栈的学习与应用
栈(Stack)是只允许在一段进行插入或删除操作的线性表
特点:后进先出(Last In First Out)
常用的命名规范:
InitList(&L):初始化栈。构造一个空栈S,分配内存空间
DestoryStack(&L):销毁栈,销毁并释放栈S所占用的内存空间
Push(&S,x):进栈
Pop(&S,&x):出栈
GetTop(&S,&x):读栈顶元素
StackEmpty(S):判断一个栈S是否为空
顺序栈的实现
#include <iostream>
#define MaxSize 10
using namespace std;
typedef struct{
int data[MaxSize];//静态数组存放栈中元素
int top;
}SqStack;
//初始化栈
void InitStack(SqStack &S){
S.top = -1;
}
//判断栈空
bool StackEmpty(SqStack S){
if(S.top == -1)
return true;
else
return false;
}
//新元素入栈
bool Push(SqStack &S, int x){
if(S.top == MaxSize-1)
return false;
S.top = S.top + 1;//指针先加1
S.data[S.top] = x;//新元素入栈
return true;
}
//出栈操作
bool Pop(SqStack &S, int &x) {
if(S.top == -1)
return false;
x = S.data[S.top];
S.top = S.top - 1;
return true;
}
//读取栈顶元素
bool GetTop(SqStack &S, int &x) {
if(S.top == -1)
return false;
x = S.data[S.top];
return true;
}