数据结构作业之表达式求值

数据结构作业,给出表达式求值(0-10整数)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*栈*/ 
typedef struct snode
{
 char data;
 struct snode *next;
}Snode,*Linkstack;

/*初始化*/ 
void initlinkstack(Linkstack &L)
{
 L=NULL;
}

/*取栈顶元素*/ 
char Linkstackgettop(Linkstack L)
{
 char a;
 if(L==NULL)
  return 0;
 a=L->data;
 return a;
} 

/*插入栈顶元素*/ 
void Linkstackpush(Linkstack &L,char a)
{
 Linkstack P=(Linkstack)malloc(sizeof(Snode));
 P->data=a;
 P->next=L;
 L=P;
}

/*删除栈顶元素*/ 
char Linkstackpop(Linkstack &L)
{
 char a;
 Linkstack P=L;
 if(L==NULL)
  return 0;
 L=L->next;
 a=P->data;
 free(P);
 return a;
}

/*比较运算符优先级*/ 
int prior(char a)
{
 if(a=='*'||a=='/')
  return 4;
 else if(a=='+'||a=='-')
  return 3;
 else if(a='(')
  return 2;
 else if(a=='#')
  return 1;
 else return 0;
}

/*计算表达式的值*/ 
void calculate(char a[])
{
 Linkstack L,P;int x1,x2;
 initlinkstack(L);
 initlinkstack(P);
 int i=0,k=0,n;char ch;
 Linkstackpush(L,'#');
 n=strlen(a);a[n]='#';a[n+1]='\0';
 while(a[i]!='\0')
 {
  if(a[i]>='0'&&a[i]<='9')
   Linkstackpush(P,a[i]-48);
  else
   switch(a[i])
   {
    case '(':Linkstackpush(L,a[i]);
      break;
    case ')': 
     ch=Linkstackpop(L);
     while(ch!='(')
     {
      switch(ch)
      {
       case '+':x2=Linkstackpop(P);x1=Linkstackpop(P);Linkstackpush(P,x1+x2);break;
       case '-':x2=Linkstackpop(P);x1=Linkstackpop(P);Linkstackpush(P,x1-x2);break;
       case '*':x2=Linkstackpop(P);x1=Linkstackpop(P);Linkstackpush(P,x1*x2);break;
       case '/':x2=Linkstackpop(P);x1=Linkstackpop(P);
         if(x2!=0)
          Linkstackpush(P,x1/x2);
         else
         {
          printf("分母是0!\n");
          return;
         }
        
         break;      
         }
         ch=Linkstackpop(L);
     }
     break;
    default:
     ch=Linkstackgettop(L);
     if(prior(ch)<=prior(a[i]))
     {
      Linkstackpush(L,a[i]);
      
     }
     else
     {
     while(prior(ch)>prior(a[i]))
     {
      ch=Linkstackpop(L);
      switch(ch)
      {
       case '+':x2=Linkstackpop(P);x1=Linkstackpop(P);Linkstackpush(P,x1+x2);break;
       case '-':x2=Linkstackpop(P);x1=Linkstackpop(P);Linkstackpush(P,x1-x2);break; 
       case '*':x2=Linkstackpop(P);x1=Linkstackpop(P);Linkstackpush(P,x1*x2);break;
       case '/':x2=Linkstackpop(P);x1=Linkstackpop(P);Linkstackpush(P,x1/x2);break;
             
         }
         ch=Linkstackgettop(L);
         
     }
     Linkstackpush(L,a[i]);    
     }
     break;
     
    
   
  } 
  i++;
 }
 printf("结果是:%d",Linkstackpop(P));
}

int main()
{
 char a[20];
 printf("输入表达式:\n");
 scanf("%s",a);
 calculate(a);
 return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值