数据结构(C++实现):栈的运用--中缀表达式转换为后缀表达式既 nyoj 257

来源:互联网 发布:软件系统测试报告用途 编辑:程序博客网 时间:2024/05/16 15:33

       这题用了c++提供的<stack>封装了,没有写手工栈,手工栈的代码等实验结束后再上传。

       题目链接http://acm.nyist.net/JudgeOnline/problem.php?pid=257

                                                   郁闷的C小加(一)

描述

我们熟悉的表达式如a+b、a+b*(c+d)等都属于中缀表达式。中缀表达式就是(对于双目运算符来说)操作符在两个操作数中间:num1 operand num2。同理,后缀表达式就是操作符在两个操作数之后:num1 num2 operand。ACM队的“C小加”正在郁闷怎样把一个中缀表达式转换为后缀表达式,现在请你设计一个程序,帮助C小加把中缀表达式转换成后缀表达式。为简化问题,操作数均为个位数,操作符只有+-*/ 和小括号。

输入
第一行输入T,表示有T组测试数据(T<10)。
每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个表达式。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。并且输入数据不会出现不匹配现象。
输出
每组输出都单独成行,输出转换的后缀表达式。
样例输入
21+2(1+2)*3+4*5
样例输出
12+12+3*45*+
#include <iostream>#include <cstdio>#include <stack>#include <cstring>#include <string>using namespace std;char str[1100];int Compare(char n_ope){    if(n_ope=='+'||n_ope=='-') return 1;    if(n_ope=='*'||n_ope=='/') return 2;    if(n_ope=='(') return 0;    return -1;}int main(){    int T;    scanf("%d",&T);    while(T--)    {        memset(str,'\0',sizeof str);        scanf(" %s",str);        const int len = strlen(str);        stack<char> s;        s.push('#');        for(int i=0;i<len;i++)        {            if(isdigit(str[i])){                printf("%c",str[i]);            }            else if(str[i]=='('){                s.push(str[i]);            }            else if(str[i]==')'){                while(s.top()!='(')                {                    printf("%c",s.top());                    s.pop();                }                s.pop();//将左括号弹出            }            else{                while(Compare(s.top())>=Compare(str[i]))                {                    printf("%c",s.top());                    s.pop();                }                s.push(str[i]);            }        }        while(s.top()!='#'){            printf("%c",s.top());            s.pop();        }        printf("\n");    }    return 0;}


0 0
原创粉丝点击