栈的应用之中缀表达式转换为后缀表达式

本文介绍了一种将中缀表达式转换为后缀表达式的算法实现,并提供了详细的代码示例。通过栈来处理运算符的优先级,确保转换过程正确无误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//思路:
//1:当读到一个操作数,立即放到后缀表达式结果中。
//2:当读到一个操作符,从存储运算符的栈中弹出元素到后缀表达式结果,直到出现级别更低的运算符为止,
//最后再把此运算符推入栈,
//但有一个例外,除非遇到),否者绝不会弹出(。
//3:当读到一个(,压入栈中。
//示例:
//中缀:a + b * c + ( d * e + f ) * g
//后缀:a b c * + d e * f + g * +
#include <stdio.h>
#include <stdlib.h>
//假设输入的中缀表达式各运算符和运算数之间均存在空格,且中缀表达式合法
char temp[100];//临时存储操作符
int topt=-1;
char result[100];//存储后缀表达式结果
int topr=-1;
int isoperator(char data[])
{
    if(strlen(data)!=1)
        return 0;
    switch(data[0])
    {
        case '+':
        case '-':
        case '*':
        case '/':
        case '(':
        case ')':return 1;
        default:return 0;
    }
}
void dealtemp(char data[])
{
    if(data[0]==')'){
        while(temp[topt]!='('){
            result[++topr]=' ';
            result[++topr]=temp[topt];
            topt--;
        }
        topt--;
    }
    else if(data[0]=='*'||data[0]=='/'){
        while(topt!=-1&&temp[topt]!='('&&temp[topt]!='+'&&temp[topt]!='-'){
            result[++topr]=' ';
            result[++topr]=temp[topt];
            topt--;
        }
        temp[++topt]=data[0];
    }
    else if(data[0]=='+'||data[0]=='-'){
        while(topt!=-1&&temp[topt]!='('){
            result[++topr]=' ';
            result[++topr]=temp[topt];
            topt--;
        }
        temp[++topt]=data[0];
    }
    else{
        temp[++topt]=data[0];
    }
}
int main()
{
    //用两个栈实现转变
    char data[100];//原始的中缀数据
    int flag=0;//决定当前字符串前添不添加空格
    while(scanf("%s",data)!=EOF){
       if(isoperator(data)){//判断是不是操作符
          dealtemp(data);
       }
       else{
         if(flag)
            result[++topr]=' ';
         strcpy(result+topr+1,data);
         topr=strlen(result)-1;
         flag=1;
       }

    }
    while(topt!=-1){
        result[++topr]=' ';
        result[++topr]=temp[topt--];
    }
    result[++topr]='\0';
    puts(result);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值