考研算法
题目
题目要求
表达式求值
代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <stack>
#include <unordered_map>
using namespace std;
stack<int> num;
stack<char> op;
unordered_map<char,int> h{{'+',1},{'-',1},{'*',2},{'/',2}};
void eval()
{
int num1=num.top();
num.pop();
int num2=num.top();
num.pop();
char opr=op.top();
op.pop();
int res=0;
if (opr=='+') res=num1+num2;
if (opr=='-') res=num2-num1;
if (opr=='*') res=num1*num2;
if (opr=='/') res=num2/num1;
num.push(res);
}
int main()
{
string s;
cin>>s;
for(int i=0;i<s.size();i++)
{
if(isdigit(s[i]))
{
int j=i;
int x=0;
while(j<s.size() && isdigit(s[j]))
{
x=x*10+s[j]-'0';
j++;
}
i=j-1;
num.push(x);
}
else if (s[i]=='(')
{
op.push(s[i]);
}
else if (s[i]==')')
{
while (op.top()!='(')
{
eval();
}
op.pop();
}
else
{
while(op.size() && h[s[i]]<=h[op.top()]){
eval();
}
op.push(s[i]);
}
}
while(op.size()) eval();
cout<<num.top();
}
s=input()
num=[]
op=[]
h={'(':0,'+':1,'-':1,'*':2,'/':2}
def val():
global num,op
r=0
num1=num.pop()
num2=num.pop()
opr=op.pop()
if opr=='+':
r=num2+num1
if opr=='-':
r=num2-num1
if opr=='*':
r=num2*num1
if opr=='/':
r=int(num2/num1)
num.append(r)
i=0
while(i<len(s)):
if s[i].isdigit():
su=0
j=i
while(j<len(s) and s[j].isdigit()):
su=su*10+int(s[j])
j=j+1
num.append(su)
i=j-1
elif s[i]=='(':
op.append(s[i])
elif s[i]==')':
while(len(op) and op[-1]!='('):
val()
op.pop()
else:
if len(op) and h[s[i]]<=h[op[-1]]:
while(len(op) and h[s[i]]<=h[op[-1]]):
val()
op.append(s[i])
i=i+1
while(len(op)):
val()
print(num.pop())
知识点
C++使用include <stack>实现栈
stack<int> num;
stack<char> op;
num.pop();//取出栈顶元素,并删除
num.top();//取出栈顶元素
num.push(res);//进栈
unordered_map<char,int> h{{'+',1},{'-',1},{'*',2},{'/',2}};//用来实现哈希表
isdigit(s[i])判断是否为数字
python使用字典实现哈希表,使用列表实现栈
列表使用append pop分别实现入栈,出栈,无top的函数
h={'(':0,'+':1,'-':1,'*':2,'/':2}