栈(运算操作)

来源:互联网 发布:windows 自带扫描软件 编辑:程序博客网 时间:2024/09/21 08:59
<a target=_blank href="http://acm.zjgsu.edu.cn/problems/94">点击打开链接</a>
<pre name="code" class="cpp">

#include<stdio.h>#include<string.h>#define MAX 1000000+10#define Min(a,b) a<b?a:bchar s[MAX];int stack[MAX];int n;char operater(int ch,int start,int e){    int sum=stack[start];    for(int i=start+1;i<e;i++){        switch(ch){            case '+'-'0':                sum+=stack[i];                break;            case '-'-'0':                sum-=stack[i];                break;            case '*'-'0':                sum*=stack[i];                break;            case '/'-'0':                sum/=stack[i];                break;        }    }    //printf("%d\n",sum);    return sum;}int  out(int e){    int i=e-1;    while(1){        if(stack[i]=='('-'0')break;        i--;    }    stack[i]=operater(stack[i+1],i+2,e);    return i+1;}void work(){    int i=0,flag=0;    for(int j=0;j<n;j++){        if(s[j]!=' '){            if(s[j]=='(')stack[i++]=s[j]-'0';            else if(s[j]==')')i=out(i);            else{                stack[i]=s[j]-'0';                while(s[j+1]>='0'&&s[j+1]<='9'){                    j++;                    stack[i]=stack[i]*10+s[j]-'0';                }                i++;            }        }    }    printf("%d\n",stack[0]);    return ;}int main(){    while(gets(s)!=NULL){        n=strlen(s);        work();    }    return 0;}/*(+ 2 (* 3 4) (- 3 5))12'('-'0'=-8'+'-'0'=-5'*'-'0'=-6'-'-'0'='\'-'0'=*/


                                             
0 0
原创粉丝点击