堆栈应用 --> 函数调用,递归,表达式求值
O(n)线性表 -->时间复杂度是线性的
特点--> 后进先出 Last in first out (LIFO)
push前应先判断栈是否满
pop前应先判断栈是否空
运用1:表达式求值
题: 6 2 / 3 - 4 2 * + = ?
解法:遇到数将其压入栈中,遇到符号则把栈中最后两个数拿出来与符号进行运算
#include<stack>
#include<iostream>
using namespace std;
stack<int> Q;
char s;
int a,b,c;
int main()
{
while(cin>>s&&s!='=')
{
a=s-'0';
if(a>=0&&a<=9) Q.push(a);
else
{
c=Q.top();
Q.pop();
b=Q.top();
Q.pop();
if(a==-5) Q.push(b+c);
else if(a==-3) Q.push(b-c);
else if(a==-6) Q.push(b*c);
else Q.push(b/c);
}
}
cout<<Q.top()<<endl;
return 0;
}