演示用算符优先法对算术表达式求值的过程.
以字符序列的形式从终端输入语法正确的,不含变量的整数表达式.实现对算术四则混合运算表达式的求值,并演示在求值中运算符栈,运算数栈,输入字符的变化过程.(是栈的应用) 谢谢了!!!
//LinStack.h #include<iostream> #include<assert.h> using namespace std; template<typename T>class stack; template<typename T>class Node{ T info; Node<T> *link; public: Node(T data=0,Node<T> *next=NULL){ info=data; link=next;} friend class stack<T>; }; template<typename T>class stack{ Node<T> *top; public: stack(){top=NULL;} ~stack(); void MakeEmpty(); void push(T data); T pop(); bool IsEmpty()const {return top==NULL;} }; template<typename T>stack<T>::~stack(){ MakeEmpty(); } template<typename T>void stack<T>::MakeEmpty(){ Node<T> *temp; while(top!=NULL) { temp=top; top=top->link; delete temp; } } template<typename T>void stack<T>::push(T data){ top=new Node<T>(data,top); } template<typename T>T stack<T>::pop(){ assert(!IsEmpty()); Node<T> *temp; temp=top; T data=temp->info; top=top->link; delete temp; return data; } #include "lianzhan.h" #include<stdlib.h> #include<iostream> using namespace std; class Calculator{ stack<int> Nstack; stack<char> Ostack; public: void Cal(); void GetNum(int &num1,int &num2); void Computer(char opr); void Cear(); }; void Calculator::Cear(){ Nstack.MakeEmpty(); Ostack.MakeEmpty(); } void Calculator::GetNum(int &num1,int &num2){ num1=Nstack.pop(); num2=Nstack.pop(); } void Calculator::Computer(char opr){ int num1,num2; if(opr!='=') GetNum(num1,num2); switch(opr){ case '+':Nstack.push(num2+num1);break; case '-':Nstack.push(num2-num1);break; case '*':Nstack.push(num2*num1);break; case '/':Nstack.push(num2/num1);break; case '=':cout<<Nstack.pop()<<endl; } } void Calculator::Cal(){ bool b1=true,b2=true; char c1,c2,str[100]; int k=-1; while(b2){ cin>>c1; if(c1>='0'&&c1<='9'){ k++; str[k]=c1; } else{ if(k>=0) { str[k+1]='\0'; Nstack.push(atoi(str)); k=-1; } switch(c1){ case 'c': Cear();break; case '+': case '-': while(!Ostack.IsEmpty()){ c2=Ostack.pop(); Computer(c2); } Ostack.push(c1); break; case '*': case '/': while(!Ostack.IsEmpty()&&b1){ c2=Ostack.pop(); if(c2=='*'||c2=='/') Computer(c2); else{ Ostack.push(c2); b1=false; } } Ostack.push(c1); b1=true; break; case '=': while(!Ostack.IsEmpty()){ c2=Ostack.pop(); Computer(c2); } Computer(c1); break; } if(c1=='z') b2=false; } } delete []str; } void main() {Calculator cal; cal.Cal(); } 输入结束符号是Z 例如 3+4*6/2+1=Z 我的程序只是得到结果,你自己加上运算过程吧