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以内,因为字符只能识别一个,为了方便,我在主函数中定义了后缀表达式,读者可以自行更改
附上结果运行图:
《C语言后缀表达式的计算--For初学者》

    原文作者:a_52hz
    原文地址: https://blog.csdn.net/a_52hz/article/details/82858645
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞