输入字符串计算式,输出结果

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

struct s_node
{
 int data;
 struct s_node *next;
};

typedef struct s_node s_list;
typedef s_list *link;
link operate = NULL;
link operand = NULL;

//存入堆栈数据
link push(link stack,int value)
{
 link newnode;
 
 newnode = (link)malloc(sizeof(s_list));
 if (!newnode)
 {
  printf("Memory allocation failure!/n");
  return NULL;
 }
 newnode->data = value;
 newnode->next = stack;
 stack = newnode;

 return stack;
}

//取出数据
link pop(link stack,int *value)
{
 link top;

 if ( NULL != stack ) 
 {
  top = stack;
  stack = stack->next;
  *value = top->data;
  free(top);
  return stack;
 }
 else
 {
  *value = -1;
 }
}

//检查堆栈是否为空
int empty(link stack)
{
 if ( NULL == stack )
 {
  return 1;
 }
 else
 {
  return 0;
 }
}

//判断是否为运算符
int is_operator(char operate)
{
 switch(operate)
 {
 case '+':
 case '-':
 case '*':
 case '/':
  return 1;
 default:
  return 0;
 }
}

//判断运算符优先权
int priority(char operate)
{
 switch(operate)
 {
 case '+':
 case '-':
  return 1;
 case '*':
 case '/':
  return 2;
 default:
  return 0;
 }
}

//计算两个操作数的值
int caculate(int operate,int operand1,int operand2)
{
 switch(operate)
 {
 case '+':
  return (operand2+operand1);
 case '-':
  return (operand2-operand1);
 case '*':
  return (operand2*operand1);
 case '/': 
  return (operand2/operand1);
 }
}

int main(void)
{
 char expression[50];
 int position=0;
 int op=0;
 int operand1=0;
 int operand2=0;
 int result=0;
 
 printf("Please input the expression:");
 gets(expression);
 printf("/n");

 while (expression[position] != '/0' && expression[position] != '/n')
 {
  if (is_operator(expression[position]))
  {
   if (!empty(operate))
   {
    while (!empty(operate)&&priority(expression[position])<priority(operate->data))
    {
     operand=pop(operand,&operand1);
     operand=pop(operand,&operand2);
     operate=pop(operate,&op);
     operand=push(operand,caculate(op,operand1,operand2));
    }
   }
   operate=push(operate,expression[position]);
  }
  else
  {
   operand=push(operand,expression[position]-48);
  }
  position++;
 }

 while (!empty(operate))
 {
  operate=pop(operate,&op);
  operand=pop(operand,&operand1);
  operand=pop(operand,&operand2);
  operand=push(operand,caculate(op,operand1,operand2));
 }
 operand=pop(operand,&result);
 printf("the expression [%s] result is '%d'/n",expression,result);

 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值