栈的基本操作(完美契合王道书)
1.顺序存储实现栈
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 50
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];//数组
int top;
}SqStack;
链表实现栈,其实用的是头部插入法和头部删除法,不重要。
2.初始化栈
//初始化栈
void InitStack(SqStack &S)
{
S.top = -1;//代表栈为空
}
3.判断栈是否为空
//判断栈是否为空
bool StackEmpty(SqStack S)
{
if (-1 == S.top)
return true;
return false;
}
4.入栈
先加加后赋值
//入栈
bool Push(SqStack &S,ElemType x)
{
if (S.top == MaxSize - 1)
return false;//栈满了
S.data[++S.top] = x;
return true;//入栈成功
}
5.获取栈顶元素
//获取栈顶元素
bool GetTop(SqStack S, ElemType& x)
{
if (StackEmpty(S))//栈为空
return false;
x = S.data[S.top];
return true;
}
6.出栈
先赋值后减减
//出栈
bool Pop(SqStack &S, ElemType &x)
{
if (StackEmpty(S))//栈为空
return false;
x = S.data[S.top--];//等价于x=S.data[S.top];再做S.top--
return true;
}
判断栈空:S.top=-1
判断栈满:S.top=MaxSize-1(因为是数组实现的)
7.主函数
//实现栈,可以用数组,也可以用链表,我们这里使用数组
int main()
{
SqStack S;//初始化一个栈
bool flag;
ElemType m;//用来存放拿出的栈顶元素
InitStack(S);//初始化
flag = StackEmpty(S);
if (flag)
printf("栈是空的\n");
Push(S, 3);//入栈元素3
Push(S, 4);//入栈元素4
Push(S, 5);
flag = GetTop(S, m);//获取栈顶元素,但是S.top值不变
if (flag)
printf("获取栈顶元素为%d\n", m);
flag = Pop(S, m);//弹出栈顶元素
if (flag)
printf("弹出元素为%d\n", m);
return 0;
}