文章目录
- 栈的基本操作
- 栈的定义
- 栈的初始化
- 栈的判空
- 进栈
- 出栈
- 读取栈顶元素
- 销毁栈
- 全部源码
栈的基本操作
以下代码中,默认初始化的top为-1。
栈的定义
#define MaxSize 50 //定义栈中元素最大个数typedef struct {int data[MaxSize]; //存放栈中元素int top; //栈顶指针
}SqStack;
栈的初始化
将top指指针指向-1.
void InitStack(SqStack &s)
{s.top = -1;
}
栈的判空
bool StackEmpty(SqStack s)
{if (s.top == -1)return true;cout << "栈不为空";return false;
}
进栈
理解这里的指针先加1,在入栈。
bool Push(SqStack& s,int e)
{if (s.top == MaxSize - 1)return false; //栈满s.data[++s.top] = e; //指针先加1,在入栈return true;
}
出栈
先出栈,指针在减1。
bool Pop(SqStack& s, int &e)
{if (s.top == -1)return false; //栈空,报错e = s.data[s.top--]; //数据e先出栈,指针在减1return false;
}
读取栈顶元素
bool GetTop(SqStack s, int &e)
{//判断栈是否为空if (s.top == -1)return false;e = s.data[s.top];return true;
}
销毁栈
bool DestoryStack(SqStack& s)
{s.top == -1;return true;
}
全部源码
#include<iostream>
using namespace std;#define MaxSize 50 //定义栈中元素最大个数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;cout << "栈不为空";return false;
}//进栈
bool Push(SqStack& s,int e)
{if (s.top == MaxSize - 1)return false; //栈满s.data[++s.top] = e;return true;
}//出栈
//数据还残留在栈中,只是在逻辑上被删除
bool Pop(SqStack& s, int &e)
{if (s.top == -1)return false; //栈空,报错e = s.data[s.top--]; //数据e先出栈,指针在减1return false;
}//读取栈顶元素
bool GetTop(SqStack s, int &e)
{if (s.top == -1)return false;e = s.data[s.top];return true;
}//栈的遍历
void PrintStack(SqStack s)
{if (s.top == -1)return;for (int i = 0; i <= s.top; ++i){cout << s.data[i]<<" ";}
}//销毁栈
bool DestoryStack(SqStack& s)
{s.top == -1;return true;
}
int main()
{SqStack s;//初始化InitStack(s);//判断栈是否为空StackEmpty(s);//进栈cout << "输入进栈的元素:";int e = 0;cin >> e;while (e != 9999){Push(s, e);cout << "输入进栈的元素:";cin >> e;}//出栈Pop(s, e);cout << "出栈的元素为:" << e<<endl;//读取栈顶元素GetTop(s, e);cout << "栈顶的元素为:" << e << endl;//打印全部元素PrintStack(s);//销毁栈DestoryStack(s);return 0;
}
对你有帮助,点个关注吧!!!