暑假集训7.29 一般表达式转换后缀表达式(手写模拟栈....)sdutoj2132
2016-07-30 10:44
288 查看
数据结构实验之栈二:一般算术表达式转换成后缀式
Time Limit: 1000MS Memory limit: 65536K
题目描述
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
输入
输入一个算术表达式,以‘#’字符作为结束标志。
输出
输出该表达式转换所得到的后缀式。
示例输入
a*b+(c-d/e)*f#
示例输出
ab*cde/-f*+
///思路
///1.如果是数字符 直接打印 (也可以保存到字符数组)因为中缀转换不改变数字符位置 i++
///2.如果栈空 运算符或括号压栈 i++
///3.栈不空 栈外元素与栈顶比较 for(;;)
///i.左括号直接压栈
/// ii.栈外元素优先级高于栈顶 将其压栈(如果栈顶是括号 也执行此步骤)
///iii.栈外元素优先级低于等于栈顶 栈顶元素出栈打印 栈外元素压栈 while():一直到3-ii.成立 即栈外元素压栈....
///iiii.栈外元素是右括号 将栈内元素依次出栈打印 直到左括号 舍弃括号 不输出
///Accode
#include <iostream> #include <cstdio> using namespace std; const int maxn=100010; typedef struct Stack { char *top,*base; int Size; }; void Creat(Stack &s) ///建栈 { s.base=new char[maxn]; s.top=s.base; } void push(Stack &s,char ch) ///压ch入栈 { s.top++; *s.top=ch; } bool Empty(Stack &s) ///是否为空 { if(s.base==s.top) { return 1; } return 0; } void pop(Stack &s) ///出栈 { if (!Empty(s)) { s.top--; } } void print(Stack &s) ///打印 { while(!Empty(s)) { cout<<*s.top; pop(s); } cout<<endl; } int change(Stack &s,char st[],int n) ///转化为后缀 { int i; for (i=1; i<=n; i++) { if (st[i]>='a'&&st[i]<='z') { cout<<st[i]; } else { if (Empty(s)) { push(s,st[i]); } else if (st[i]=='+'||st[i]=='-')/// step 3—iii { while (*s.top=='*'||*s.top=='/'||*s.top=='+'||*s.top=='-') { cout<<*s.top; s.top--; } push(s,st[i]);/// step 3-ii } else if(st[i]=='*'||st[i]=='/')/// step 3-iii { while(*s.top=='*'||*s.top=='/') { cout<<*s.top; s.top--; } push(s,st[i]);/// step 3-ii } else if (st[i]==')') { while(*s.top!='(') { cout<<*s.top; pop(s); } pop(s);///舍弃左括号 } else if (st[i]=='(') { push(s,st[i]); } } } } int main() { char ch,st[maxn]; int i=0; Stack s; Creat(s); while(ch=getchar()) { if(ch!='#')///读取#结束 { i++; st[i]=ch; } else if(ch=='#') { break; } } change(s,st,i); /// 表示字符串下标1--i print(s); return 0; }
相关文章推荐
- 一些OJ网站
- 图解后缀表达式的计算过程
- 接触后缀表达式(逆波兰表示法)
- 【OJ日志】超级约瑟夫
- 【OJ日志】爬楼梯
- 【OJ日志】删除升序数组的重复数字
- 几个比较大的在线提交系统(Online Judge)
- 初学ACM - 半数集(Half Set)问题 NOJ 1010 / FOJ 1207
- LeetCode-Rotate Array
- LeetCode-Sudoku Solver
- LeetCode-Minimum Window Substring
- 前缀表达式,中缀表达式,后缀表达式转化和计算
- HDU 1000
- HDU 1001
- 中缀表达式与后缀表达式
- sjtu online judge 1034 二哥的金链
- hdu 1005 -- Number Sequence
- 大整数加减法
- leetCode题解:AddDigits
- 题目1448:Legal or Not