跳到正文

个人记录

栈进阶--表达式问题

zqrmon约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年7月21日
收录
2025年12月12日
更新
2026年11月9日
篇幅
约 5 分钟

版本

  1. v1当前

U445194 栈进阶—3 后缀表达式求值

C++
#include<bits/stdc++.h>
using namespace std;
int d=0;
stack<int>st;
int main(){
	string a;
	while(cin>>a){
		if(a[0]=='@'){
			break;
		}
		if(a[0]>='0'&&a[0]<='9'){//判断是否是数字
			int b=1;
			for(int i=0;i<a.size()-1;i++){
				b*=10;
			}
			int c=0;
			for(int i=0;i<a.size();i++){
				c+=(a[i]-'0')*b;
				b/=10;
			}
			st.push(c);
		}else{
			int b=st.top();
			st.pop();
			int c=st.top();
			st.pop();
			if(a[0]=='/'){
				st.push(c/b);
			}if(a[0]=='*'){
				st.push(c*b);
			}if(a[0]=='-'){
				st.push(c-b);
			}if(a[0]=='+'){
				st.push(c+b);
			}
		}
	} 
	cout<<st.top();
	return 0;
}

U445233 栈进阶—5 表达式求值

C++
#include <bits/stdc++.h>
using namespace std;
stack <int> st;
int a,b;
char c;
int main()
{
	cin>>a;
	a=a%10000;
	st.push(a);
	while(cin>>c>>b)
	{
		if(c=='*')
		{
			a=st.top();
			st.pop();
			st.push(a*b%10000);
		}
		else
		{
			st.push(b);
		}
	}
	a=0;
	while(st.size())
	{
		a+=st.top();
		a%=10000;
		st.pop();
	}
	cout<<a<<endl;
	return 0;
}

U445242 栈进阶—6 中缀转后缀表达式

C++
#include <bits/stdc++.h>
using namespace std;
stack <char> st;
string s;
map<char,int>mp;
int main()
{
	mp['(']=0,mp['+']=1,mp['-']=1,mp['*']=2,mp['/']=2;
	cin>>s;
	for(int i=0;i<s.size();i++){
		if(s[i]>='a'&&s[i]<='z'){
			cout<<s[i];
		}else{
			if(s[i]=='('){
				st.push(s[i]);
			}
			else if(s[i]==')'){
				while(st.top()!='('){
					cout<<st.top();
					st.pop();
				}
				st.pop();
			}else {
				while(st.size()!=0 && mp[s[i]]<=mp[st.top()]){
					cout<<st.top();
					st.pop();
					if(st.size()==0){
						break;
					}
				}
				st.push(s[i]);
			}
		}
	}
	while(st.size()>=1){
		cout<<st.top();
		st.pop();
	}
	return 0;
}

P1739 表达式括号匹配

C++
#include<bits/stdc++.h>
int a,b;
char c[10005];
using namespace std;
int main(){
	cin>>c;
	for(int i=0;i<strlen(c);i++){	
		if(c[i]==')') b++;
		if(b>a){
			cout<<"NO";
			return 0;
		} 
		if(c[i]=='(') a++;
	}
	if(a!=b) cout<<"NO";
	else 	 cout<<"YES";
	return 0;
}

P1981 [NOIP 2013 普及组] 表达式求值

C++
#include <bits/stdc++.h>
using namespace std;
stack <int> st;
int a,b;
char c;
int main()
{
	cin>>a;
	a=a%10000;
	st.push(a);
	while(cin>>c>>b)
	{
		if(c=='*')
		{
			a=st.top();
			st.pop();
			st.push(a*b%10000);
		}
		else
		{
			st.push(b);
		}
	}
	a=0;
	while(st.size())
	{
		a+=st.top();
		a%=10000;
		st.pop();
	}
	cout<<a<<endl;
	return 0;
}
原文