1. 顺序栈
用顺序存储方式实现的栈
2.基本操作
(1)顺序栈的定义
//顺序栈的定义
#define MaxSize 10
typedef struct SqStack
{
int data[MaxSize];
int top;//栈顶指针,存放着从栈底开始的栈顶元素的值的下标值。
};
(2)初始化栈
//初始化栈
void InitStack(SqStack &S)
{
S.top = -1;//初始化栈顶指针
}
(3)进栈实现
//进栈实现
bool Push(SqStack &S, int x)
{
if (S.top == MaxSize - 1)
return false;
//S.top = S.top + 1;//栈顶指针加1
//S.data[S.top] = x;//数据进栈
S.data[++S.top] = x;//与上述等效
}
(4)出栈实现
//出栈操作
bool Pop(SqStack &S, int &x)
{
if (S.top == -1)
return false;
/*x = S.data[S.top];
S.top--;*/
x = S.data[S.top--];
return true;
}
(5)读取栈顶元素
//读取栈顶元素
bool GetTop(SqStack &S, int &x)
{
if (S.top == -1)
return false;
/*x = S.data[S.top];
S.top--;*/
x = S.data[S.top];
return true;
}
3. 顺序栈的缺点
栈的大小不可变。