数据结构实验之栈二:一般算术表达式转换成后缀式
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
Input
输入一个算术表达式,以‘#’字符作为结束标志。
Output
输出该表达式转换所得到的后缀式。
Example Input
a*b+(c-d/e)*f#
Example Output
ab*cde/-f*+
Hint
思路:用一个字符数组记录答案。1.如果是字母直接读入。
2.如果是运算符,第一个是直接入栈的。
按照优先级这里括号最低,然后是+、-,最后是*,/最高。
首先是如果当前的运算符的优先级小于等于栈顶元素低,那么栈顶元素出栈,当前运算符进栈,否则直接进栈。
3.如果是左括号,那么到右括号的时候如果括号内部的运算符是应该全部出栈的
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const int MAXN=10000+5;
char s[MAXN];
char st1[MAXN];
char st2[MAXN];
int cmp(char a)
{
if(a=='+'||a=='-')return 1;
if(a=='*'||a=='/')return 2;
return 0;
}
int main()
{
scanf("%s",s);
int i=0,top1=0,top2=0;
while(s[i]!='#')
{
if(isalpha(s[i]))st1[top1++]=s[i];
else if(!top2)st2[top2++]=s[i];
else if(s[i]=='(')st2[top2++]=s[i];
else if(s[i]==')')
{
while(st2[top2-1]!='(')st1[top1++]=st2[--top2];
--top2;
}
else if(cmp(s[i])<=cmp(st2[top2-1]))
{
st1[top1++]=st2[--top2];
st2[top2++]=s[i];
}
else st2[top2++]=s[i];
i++;
}
while(top2)
{
st1[top1++]=st2[--top2];
}
st1[top1]=0;
puts(st1);
return 0;
}
/***************************************************
Result: Accepted
Take time: 0ms
Take Memory: 160KB
Submit time: 2016-09-19 10:45:20
****************************************************/