C语言后缀表达式的计算--For初学者

上次写了中缀转后缀,这次来计算后缀表达式的值,书接上文click here
思路很简单,先扫描输入的后缀表达式,遇到数字就进栈,遇到运算符就出两个栈顶的元素运算,运算的结果再入栈。直到扫描完,并且栈内只剩下一个元素,进行输出。
描绘的可能不清楚,直接上代码:


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

#define MAX 100
typedef int ElemType;
typedef struct node {
  ElemType date;
 struct node *next;
} StackNode;

void InitStack(StackNode **p) {//栈的声明
    (*p)=NULL;
}

int StackEmpty(StackNode *p) {//如果栈是空的返回0;不空返回1
    if(p==NULL)
        return 0;
    return 1;
}

void Push(StackNode **top, ElemType x) {//入栈操作
   StackNode *p;
   p=(StackNode *)malloc(sizeof(StackNode));
   p->date=x;
   p->next=*top;
   *top=p;
}

void Pop(StackNode **top, ElemType *x) {//出栈操作
    StackNode *p;
    if(*top==NULL)
        printf("Stack is empty!\n");
    else{
        *x=(*top)->date;
        p=*top;
        *top=(*top)->next;
        free(p);
    }

}

int Calc(char *s) {
    StackNode *p;
    InitStack(&p);
     ElemType x1,x2;
    int i=0,x;
    while(s[i])//进行四则运算
    {
        if(s[i]>='0'&&s[i]<='9')
            Push(&p,s[i]-48);
        else{
            Pop(&p,&x1);
            Pop(&p,&x2);
            if(s[i]=='+')
                Push(&p,x1+x2);
            if(s[i]=='-')
                Push(&p,x1-x2);
            if(s[i]=='*')
                Push(&p,x1*x2);
            if(s[i]=='/')
                Push(&p,x1/x2);
        }
        i++;
    }
    return p->date;
}

int main() {
  // (5+3)*2+(6+3) = 25
  char str[100] = "53+2*63++";//读者可以自行更改
  int rst;
  rst = Calc(str);
  printf("the results is: %d\n", rst);
  return 0;
}

本人能力有限,运行时难免有bug,请正确输入,输入的数要在10以内,因为字符只能识别一个,为了方便,我在主函数中定义了后缀表达式,读者可以自行更改
附上结果运行图:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值