栈:
一种后进先出(LIFO)的数据结构
实现栈需要:数组+指向栈顶的普通变量(可以看成手指,或者是指针)
数组 a 和变量 top:
元素 1 准备入栈:
top往前移动一位,放进去 1 :
元素 2 入栈,同理:
接下来,出栈,根据规则,只能是栈顶元素(即top指向元素)出栈:
返回top所指元素即可,但记得要把top往后移动一位。
所以栈有两个基本操作函数:
入栈:
出栈:
于是我们根据栈的特性,来写上一题逆波兰表达式的代码:
#include<iostream>
using namespace std;
const int maxn=100;
int a[maxn];
int top;
//把x压入栈
void push(int x)
{
top++;
a[top]=x;
}
//弹出栈顶元素
int pop()
{
top--;
return a[top+1];
}
//字符串转换为数字
int trans(string s)
{
int sum=0;
for(unsigned int i=0; i<s.length(); i++)
{
sum=sum*10+s[i]-'0';
}
return sum;
}
int main()
{
top=0;//把栈给清空。(但实际内存中还有)
string temp;
int a,b;
while(cin>>temp)
{
if(temp=="+")
{
a=pop();
b=pop();
push(a+b);
}
else if(temp=="-")
{
a=pop();
b=pop();
push(b-a);
}
else if(temp=="*")
{
a=pop();
b=pop();
push(a*b);
}
else//那就是数字了
{
int num=trans(temp);//把字符串变成数字
push(num);
}
}
cout<<pop()<<endl;
return 0;
}
运行结果:
下一篇讲一下实战中使用栈。