数据结构实验之栈二:一般算术表达式转换成后缀式

本文介绍了一种将包含二元运算符的一般算术表达式转换为后缀式的算法实现。通过栈的数据结构处理运算符优先级,实现了从标准中缀表达式到后缀表达式的转换。

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

数据结构实验之栈二:一般算术表达式转换成后缀式

Time Limit: 1000MS  Memory Limit: 65536KB
Problem Description
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
Input
输入一个算术表达式,以‘#’字符作为结束标志。
Output
输出该表达式转换所得到的后缀式。
Example Input
a*b+(c-d/e)*f#
 
Example Output
ab*cde/-f*+
#include<stdio.h>
int change(char c)
{
    if(c=='+'||c=='-') return 1;
    if(c=='*'||c=='/') return 2;
    if(c=='(') return 3;
    if(c==')') return 4;
    return 0;
}
int main()
{
    char c;
    int i,j,k;
    char stack[110];
    int top=-1;
    while(~scanf("%c",&c),c!='#')
    {
        if(c>='a'&&c<='z')
            printf("%c",c);
        else
        {
            if(top==-1)
                stack[++top]=c;
            else
            {
                if(change(stack[top])<change(c))
                {
                    if(c==')')
                        {
                            while(stack[top]!='(')
                            {
                               printf("%c",stack[top]);
                               top--;
                            }
                            top--;
                        }
                        else
                        {
                            stack[++top]=c;
                        }
                }
                else
                {
                    if(stack[top]=='(')
                    {
                        stack[++top]=c;
                    }
                    else
                        {
                            printf("%c",stack[top]);
                            stack[top]=c;
                        }
                }

            }
        }
    }
    while(top!=-1)
    {
        printf("%c",stack[top]);
        top--;
    }

    printf("\n");
    return 0;
}


/***************************************************
Result: Accepted
Take time: 0ms
Take Memory: 108KB
Submit time: 2016-10-07 21:41:56
****************************************************/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值