实验之栈二:一数据结构般算术表达式转换成后缀式

来源:互联网 发布:linux oracle登录命令 编辑:程序博客网 时间:2024/06/11 09:33

实验之栈二:一数据结构般算术表达式转换成后缀式

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic

Problem Description

对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。

Input

输入一个算术表达式,以‘#’字符作为结束标志。

Output

输出该表达式转换所得到的后缀式。

Example Input

a*b+(c-d/e)*f#

Example Output

ab*cde/-f*+

Hint

 

Author

 
AC:
#include<stdio.h>#include <algorithm>#include <stdlib.h>#include <string.h>#include <stack>                          //栈所在的头文件using namespace std;int main(){    stack<char>st;    char sta[150];    while(scanf("%s", sta) != EOF)    {        for(int i = 0; sta[i] != '#'; i++)        {            if(sta[i] >= 'a' && sta[i] <= 'z')  //如果是字母则直接输出不进栈                printf("%c", sta[i]);            else if(sta[i] == '(')          //如果是左括号则直接进栈                st.push(sta[i]);            else if(sta[i] == ')')          //如果是右括号则把栈里左括号之上的符号全部输出            {                while(st.top() != '(')                {                    printf("%c", st.top());                    st.pop();                }                st.pop();                 //左括号虽不输出但要记得把它从栈里移除            }            else if(sta[i] == '+' || sta[i]=='-')   //‘+’与‘-’的优先级低于‘*’与‘/’,所以要先输出‘*’或‘/’,然后再把‘+’或‘-’放入栈中            {                while(!st.empty() && st.top() != '(')                {                    printf("%c", st.top());                    st.pop();                }                st.push(sta[i]);            }            else if(sta[i] == '*' || sta[i] == '/')            {                while(!st.empty() && st.top() != '('&&(st.top() == '*' || st.top() == '/'))                {                    printf("%c", st.top());                    st.pop();                }                st.push(sta[i]);            }        }        while(!st.empty())               //若栈不为空记得把栈内的符号全部输出        {            printf("%c", st.top());            st.pop();        }        printf("\n");    }    return 0;}


阅读全文
0 0