2.2栈

来源:互联网 发布:网络大电影招商案 编辑:程序博客网 时间:2024/05/21 05:42

头文件 SeqStack.h:

#include<iostream>using namespace std;#define MAXSIZE 100typedef double DataType;typedef struct{DataType data[MAXSIZE];int top;}SeqStack,*PSeqStack;//初始化栈PSeqStack Init_SeqStack(void){PSeqStack S;S=(PSeqStack)malloc(sizeof(SeqStack));if(S){S->top=-1;}return S;}//判断栈空(是否有元素)int Empty_SeqStack(PSeqStack S){if(S->top==-1)return 1;elsereturn 0;}//入栈(在栈顶插入元素)int Push_SeqStack(PSeqStack S,double x){if(S->top==MAXSIZE-1)return 0;else{S->top++;S->data[S->top]=x;return 1;}}//出栈(删除顶部元素)int Pop_SeqStack(PSeqStack S,double *x){if(Empty_SeqStack(S))return 0;else{*x=S->data[S->top];S->top--;return 1;}}//取栈顶元素(不删除)int GetTop_SeqStack(PSeqStack S,double *x){if(Empty_SeqStack(S))return 0;else{*x=S->data[S->top];return 1;}} //销毁栈void Destroy_SeqStack(PSeqStack *S){if(*S)free(*S);*S=NULL;return ;}


后缀表达式计算 源文件:

#include<iostream>#include"SeqStack.h"using namespace std;typedef double DataType;int IsNum(char c)//判断字符是否为操作数{if(c>='0'&&c<='9')return 1;else return 0;}double postfix_exp(char *A)//本函数返回由后缀表达式表示的运算结果{PSeqStack S;//栈中存储操作数double Result,a,b,c;char ch;ch=*A++;S=Init_SeqStack();//初始化栈while(ch!='#'){if(IsNum(ch)) Push_SeqStack(S,ch-'0');else{Pop_SeqStack(S,&b);Pop_SeqStack(S,&a);switch(ch){    case '+':c=a+b;break;case '-':c=a-b;break;case '*':c=a*b;break;case '/':c=a/b;break;    //case '%':c=(int)a%(int)b;break;//case '^':c=pow(a,b);break;}Push_SeqStack(S,c);}ch=*A++;}GetTop_SeqStack(S,&Result);Destroy_SeqStack(&S);return Result;}int main(){PSeqStack S;S=Init_SeqStack();    Destroy_SeqStack(&S);    cout<<postfix_exp("1285-*+42/-#");//5return 0;}


 

 

0 0
原创粉丝点击