简介
- 利用一组地址连续的存储单元依次自栈底到栈顶存放栈的数据元素
- 可以解决一些顺序问题或括号匹配问题
- 相关题目: 大一寒假训练七(栈)2020.01.06
数组模拟栈
在数组上实现时,栈底位置可以设置在数组的任一个端点,而栈顶是随着插入和删除而变化的,可以用一个整形变量 top 存放栈顶的指针,数据入栈或出栈时使整形变量 top 分别加1或减1。
Code
注意:部分题目 top--
之前必须判断 top 是否大于等于 0,避免数组越界访问
#include <stdio.h>
int main()
{
int stack[10086],top=0;
stack[top++]=5; //入栈
stack[top++]=10;
printf("栈中有 %d 个元素\n",top);
printf("栈顶元素为 %d\n\n",stack[top-1]);
top--; //出栈
printf("栈中有 %d 个元素\n",top);
printf("栈顶元素为 %d\n\n",stack[top-1]);
if(top>0)printf("栈不是空的!\n");
else printf("栈是空的!\n");
top--;
if(top>0)printf("栈不是空的!\n");
else printf("栈是空的!\n");
return 0;
}
C++ STL 中的栈
头文件 #include <stack>
需要使用 std 命名空间 using namespace std;
- 初始化 (定义) 栈
stack<int> sta;
- 入栈
sta.push(x)
- 出栈
sta.pop()
- 判断栈是否为空
sta.empty()
- 获取栈中元素数量
sta.size()
- 取得栈顶元素
sta.top()
Code
注意:部分题目 sta.pop()
之前必须判断 sta 是否为空
对空栈进行出栈操作会产生 Runtime Error
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> sta;
sta.push(5); //入栈
sta.push(10);
cout<<"栈中有 "<<sta.size()<<" 个元素"<<endl;
cout<<"栈顶元素为 "<<sta.top()<<endl<<endl;
sta.pop(); //出栈
cout<<"栈中有 "<<sta.size()<<" 个元素"<<endl;
cout<<"栈顶元素为 "<<sta.top()<<endl<<endl;
if(sta.empty())cout<<"栈是空的!"<<endl;
else printf("栈不是空的!\n");
sta.pop();
if(sta.empty())cout<<"栈是空的!"<<endl;
else printf("栈不是空的!\n");
return 0;
}