您的位置:首页 > 其它

PTA 3.11表达式转换

2017-08-23 17:42 405 查看
有一个测试点过不了,希望大家指点。/*
* 1.cpp
*
* Created on: 2017年8月23日
* Author: Administrator
*/

#include <bits/stdc++.h>
using namespace std ;
int main()
{
string s;
cin>>s;
stack<char> st;
bool flag = false;
for( int i = 0; i < s.length()&&s.length()<=20; i++){
// 负数情况
if( i == 0 && s[i] == '-'){
cout<<s[i];
}
// 多位数及小数
else if(isdigit(s[i])||s[i]=='.')
{
if(i>0&&(isdigit(s[i-1])||s[i-1]=='.')){
cout<<s[i];
}
else if(!flag){
flag = true;
cout<<s[i];
}
else{
cout<<" "<<s[i];
}
}
// 左括号
else if(s[i]=='('){
st.push(s[i]);
}
// 右括号
else if(s[i]==')'){
while(st.top()!='('){
if(!flag)
{
flag = true;
cout<<st.top();
}
else
{
cout<<" "<<st.top();
}
st.pop();
}
st.pop();
}
// +,— 号
else if(s[i]=='+'||s[i]=='-'){
// 括号内有负数,直接输出
if(s[i-1]=='('){
if(s[i]=='-'){
if(!flag)
{
flag = true;
cout<<s[i]<<s[i+1];
i++;
}
else
{
cout<<" "<<s[i]<<s[i+1];
i++;
}
}
}
// 优先级问题
else{
if(!st.empty()){
while(!st.empty()&&(st.top()=='*'||st.top()=='/')){
if(!flag)
{
flag = true;
cout<<st.top();
}
else
{
cout<<" "<<st.top();
}
st.pop();
}

while(!st.empty()&&(st.top() == '+' || st.top() == '-')){
if(!flag)
{
flag = true;
cout<<st.top();
}
else
{
cout<<" "<<st.top();
}
st.pop();
}
}
st.push(s[i]);
}
}
// *、/号
else if(s[i]=='*'||s[i]=='/'){
if(!st.empty()){
while(!st.empty()&&(st.top()=='*'||st.top()=='/')){
if(!flag)
{
flag = true;
cout<<st.top();
}
else
{
cout<<" "<<st.top();
}
st.pop();
}
}
st.push(s[i]);
}

}

while(!st.empty()){
if(!flag)
{
flag = true;
cout<<st.top();
}
else
{
cout<<" "<<st.top();
}
st.pop();
}
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: