C++中缀表达式转后缀表达式,如何转换括号呀! 改了一天啦
C++中缀表达式转后缀表达式,怎么转换括号呀! 改了一天啦
高手指点下!~实在头疼啦.
------解决方案--------------------
后缀表达式好像不需要括号吧
------解决方案--------------------
后缀不用括号,函数priority中括号的值应最低不是最高,碰到括号就进栈,你试试
- C/C++ code
#include <iostream> #include <string> using namespace std; string RPN; char END='#',push='#'; int priority(char &ch){ switch(ch){ case '^': return 5; case '(': return 4; case ')': return 3; case '*': case '/': return 2; case '+': case '-': return 1; case '#': return -1; default: return 0; } } typedef struct SNode{ struct SNode *top; char ch; struct SNode *next; }*StackList; typedef StackList operators; void InitStack(operators &P){ SNode *node=(SNode*)malloc(sizeof(SNode)); node->top=NULL; node->ch='#'; node->next=NULL; P->top=node; } void PushStack(operators &P,char &ch){ cout<<"top:"<<P->top->ch<<"----Push:"<<ch<<endl; SNode *node=(SNode*)malloc(sizeof(SNode)); node->top=NULL; node->ch=ch; node->next=P->top; P->top=node; } void PopStack(operators &P,char &ch){ ch=P->top->ch; P->top=P->top->next; cout<<"Pop:"<<ch<<endl; } void PrintStack(operators &P){ char ch='\0'; while(P->top->ch!=END){ PopStack(P,ch); if(ch!='('&&ch!=')') RPN+=ch; if(priority(P->top->ch)<priority(push)){ push='#'; break; } } if(P->top->ch=='('&&push!='('){ PopStack(P,ch); } cout<<RPN<<endl; } void convert(operators &P,char &ch){ cout<<"----------ing"<<ch<<endl; char temp=P->top->ch; if(priority(ch)){ if(priority(temp)<priority(ch)){ if(ch=='(') END='('; PushStack(P,ch); if(ch==')') PrintStack(P); }else{ push=ch; PrintStack(P); PushStack(P,ch); } }else RPN+=ch; } int main(){ operators P=(operators)malloc(sizeof(operators)); P->top=NULL; P->ch=NULL; P->next=NULL; InitStack(P); string str; char ch='\0'; cout<<"请输入中缀表达式:"<<endl; cin>>str; for(short i=0;i<str.length();i++){ ch=str[i]; if(ch==' ') continue; convert(P,ch); } END='#'; PrintStack(P); return 0; }
高手指点下!~实在头疼啦.
------解决方案--------------------
后缀表达式好像不需要括号吧
------解决方案--------------------
后缀不用括号,函数priority中括号的值应最低不是最高,碰到括号就进栈,你试试