四则运算

#include<stdio.h>
#include<malloc.h>
typedef struct stack
{
 char data;
 struct stack *next;
}stack;

stack* init(stack *h)
{
 h=(stack *)malloc(sizeof(struct stack));
 h->next=NULL;
 return h;
}

stack* push(stack *h,char d)
{
 stack *p;
 p=(stack *)malloc(sizeof(struct stack));
 p->data=d;
 p->next=h;
 h=p;
 return h;
}

char pop(stack *h)
{
 char d;
 if(h->next!=NULL)
 {
  d=h->data;
  h=h->next;
 }
 else return NULL;
 return d;
}

int judge(char s)
{
 switch(s)
 {
 case '+':return 1;
 case '-':return 1;
 case '*':return 1;
 case '/':return 1;
 default: return 0;
 }
}

int prior(char s1)
{
 switch(s1)
 {
 case '*':return 1;case '/':return 1;
 default :return 0;
 }
}

int cout(char s,int a,int b)
{
 switch(s)
 {
 case '*':return a*b;
 case '/':return b/a;
 case '+':return a+b;
 case '-':return b-a;
 default :return 0;
 }
}
void main()
{
 char *s,d,t,*p;
 int a,b,c;
 stack *h,*l;
 s=(char *)malloc(sizeof(char)*20);
 p=s;
 h=init(h);
 l=init(l);
 gets(s);
 while(*s!='/0')
 {
     d=*s;
  if(judge(d))
  {
   t=pop(h);
   if(t)
   if(prior(d)<=prior(t))
   {
  a=pop(l);l=l->next;
  b=pop(l);l=l->next;
  //printf("%d",b);
        //printf("%c",t);
  //printf("%d",a);
        c=cout(t,a,b);
  //printf("=%d/n",c);
  l=push(l,c);
  h=h->next;
   }
   h=push(h,d);
  }
  else
  l=push(l,d-48);
  s++;
 }
  while(h->next&&l->next)
  {
   d=pop(h);
   a=pop(l);l=l->next;
   b=pop(l);l=l->next;    
   //printf("%d",b);
   //printf("%c",d);
   //printf("%d",a);
   c=cout(d,a,b);
   //printf("=%d/n",c);
   l=push(l,c);
   h=h->next;
  }
  c=pop(l);
  printf("%s=%d",p,c);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值