C++利用链栈实现中缀表达式转换后缀表达式

来源:互联网 发布:人体工学椅有用吗 知乎 编辑:程序博客网 时间:2024/06/05 11:37
#include<iostream>#include<stdio.h>#include<string.h>using namespace std;class node{private:char item;node*next;public:node(char x);char getItem();friend class node_stack;};node::node(char x){this->item=x;this->next=NULL;}char node::getItem(){return item;}class node_stack{private:node *top;public:node_stack();    bool judgeEmpty();void pop();void push(char x);void show();char  getTop();};node_stack::node_stack(){top=NULL;}bool node_stack::judgeEmpty(){if(top==NULL){return true;}return false;}void node_stack::push(char x){node *n=new node(x);n->next=top;top=n;}void node_stack ::pop(){if(judgeEmpty()){cout<<"stack empty"<<endl;return;}top=top->next;}void node_stack :: show(){if(judgeEmpty()){cout<<"stack empty"<<endl;return;}node *q=top;do {cout<<q->item<<endl;q=q->next;} while (q!=NULL);}char node_stack:: getTop(){if(judgeEmpty()){return NULL;}return top->item;}int judgePower(char s){int x;switch (s){case '+':x=1;break;    case '-':x=1;break;case '*':x=2;break;case '/':x=2;break;default:x=0;}return x;}void transform(char *p){node_stack n;for(int i=0;i<strlen(p);i++){if(p[i]>='0'&&p[i]<='9'){cout<<p[i]<<endl;continue;}else{if(n.judgeEmpty()||n.getTop()=='('||n.getTop()==')'||p[i]=='('){n.push(p[i]);continue;}if(p[i]==')'){do {cout<<n.getTop()<<endl;n.pop();} while (n.getTop()!='(');if(n.getTop()=='('){n.pop();}continue;}if(!n.judgeEmpty()&&(p[i]=='+'||p[i]=='-'||p[i]=='*'||p[i]=='/')){if(judgePower(n.getTop())>=judgePower(p[i])){do {cout<<n.getTop()<<endl;n.pop();} while (judgePower(n.getTop())>=judgePower(p[i]));}n.push(p[i]);}}}n.show();}int main(){char p[10000];gets(p);transform(p);system("pause");return 0;}

阅读全文
0 0