栈应用后缀表达式计算.docx_第1页
栈应用后缀表达式计算.docx_第2页
栈应用后缀表达式计算.docx_第3页
栈应用后缀表达式计算.docx_第4页
免费预览已结束,剩余1页可下载查看

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

后缀表达式计算LinkStack.cpp#includeusing namespace std;/单链表的结点结构体:template struct Node DataType data; Node *next; /带头结点的单链表类的声明template class LinkStack public: LinkStack( ) top=NULL; /构造函数 LinkStack( ); /析构函数 bool IsEmpty( ); /栈空操作 DataType GetTop ( ); /得到栈顶值操作 void Push( DataType x ); /进栈操作 DataType Pop( ); /出栈操作 private: Node *top;/析构函数,析构函数将单链表中所有结点的存储空间释放。template LinkStack : LinkStack( ) Node *q; while (top !=NULL) q = top; /暂存释放结点 top = top-next; /top指向被释放结点的下一个结点 delete q; /释放结点 cout链表已经删除。endl;/栈空返回true,否则返回falsetemplate bool LinkStack:IsEmpty() return (top=NULL)?true:false;/进栈操作template void LinkStack: Push( DataType x ) Node *s;s=new Node; /申请一个数据成为x的结点ss-data=x;s-next=top; top=s;/出栈操作template DataType LinkStack:Pop( ) Node *p; DataType x; if (IsEmpty() cout 栈空无值弹出 data; p=top;top=top-next;delete p;return x; ;/返回栈顶值操作 template DataType LinkStack:GetTop( ) if (IsEmpty() cout 栈空无值 data; ;PostExp.cpp#include LinkStack.h/后缀表达式计算的栈类声明template class PostExp public:PostExp( ) ; /构造函数 void Run( ); /执行表达式计算 void Clear( ); /清栈操作 private: LinkStack s; /栈对象svoid Enter( DataType num); /进栈操作bool In(char op); /判断操作数bool GetTwoOperands(DataType& operand1,DataType& operand2); /从栈中推出两个操作数void Compute(char op); /形成运算指令,进行计算;/进栈操作template void PostExp:Enter( DataType num)s.Push(num); /将操作数的值num进操作数栈/从栈中推出两个操作数template bool PostExp:GetTwoOperands(DataType& operand1,DataType& operand2) if(s.IsEmpty() /判断栈是否空cout 缺少右操作数 endl; return false;operand1=s.Pop();if(s.IsEmpty() cout 缺少左操作数 endl; return false;operand2=s.Pop(); /去左操作数return true;/形成运算指令,进行计算template void PostExp:Compute(char op)bool retult;DataType operand1,operand2;retult=GetTwoOperands(operand1,operand2); /取两个操作数if(retult=true) /如果操作数取成功,计算并进栈 switch( op ) case +: s.Push(operand2 + operand1); break; case -: s.Push(operand2 - operand1); break; case *: s.Push(operand2 * operand1); break; case /: if(operand1=0) cout 除数为零 endl; exit(1); else s.Push(operand2 / operand1); break; else s.LinkStack();/判断操作数template bool PostExp:In(char op) /判断操作数 switch( op ) /是操作符进行计算 case + : case - : case * : case / : return true; default : return false; /执行表达式计算template void PostExp:Run( )char ch;DataType newOperand;cout 输出后缀表达式,以#结束; ch,ch!=#) if(In(ch) Compute(ch); else /不是操作符,不进行计算 cin.putback(ch); /把字符放回操作流cinnewOperand; /从新读操作数Enter(newOperand); /将操作数放入栈中 if(! s.IsEmpty()cout 后缀表达式是: s.GetTop()end

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论