SWUST OJ 1042 中缀表式转化为后缀表达式

学习数据结构中缀表达式转化为后缀表达式时,数中的相关代码绝大部分都有,但是相信大家还是可能出现wrong answer的情况,特此分享这个代码,因为我真的错太多次了,发这个文章就当我的心酸历程吧!
完整代码如下:
(用数组的方法也可以做,但是我的目的是想要学习新的方式和巩固学习效果)
(我们学校学的是清华大学出版的数据结构,讲的比较详细,b站上也有很多数据结构课程的课程,我们老师推荐的是李春葆的)

#include <iostream>
#include<string.h>
using namespace std;

typedef struct node
{
    char data;
    node *next;
}node;
char ho[100];
char str[100];
void init(node *&L)
{
    L=(node *)malloc(sizeof(node));
    L->next=NULL;
}
void enter(node *&L,char x)
{
    node *p;
    p=(node *)malloc(sizeof(node));
    p->data=x;
    p->next=L->next;
    L->next=p;
}
bool out(node *&L,char &tem)
{
    if(L->next==NULL)return false;
    node *p=L->next;
    tem=p->data;
    L->next=L->next->next;
    free(p);
    return true;
}
bool get(node *&L,char &x)
{
    if(L->next==NULL)return false;
    x=L->next->data;
    return true;
}
void destory(node *&L)
{
    node *pre=L;node *p=L->next;
    while(p!=NULL)
    {
        free(pre);
        pre=p;
        p=p->next;
    }
    free(pre);
}
bool empt(node *&L)
{
    return (L->next==NULL);
}
void trans(char *str,char ho[])
{
    node *op;
    init(op);
    int cnt=0;char tem;
    while(*str!='\0')
    {
        switch(*str)
        {
            case '(':
                   enter(op,'(');
                   str++;break;
            case ')':
                out(op,tem);
                while(tem!='(')
                {
                    ho[cnt++]=tem;
                    out(op,tem);
                }
                str++;break;
            case '+':
            case '-':
                while(!empt(op))
                {
                    get(op,tem);
                    if(tem!='(')
                    {
                        out(op,tem);
                        ho[cnt++]=tem;
                    }
                    else break;
                }
                enter(op,*str);
                str++;break;
            case '*':
            case '/':
                while(!empt(op))
                {
                    get(op,tem);
                    if(tem=='*'||tem=='/')
                    {
                        out(op,tem);
                        ho[cnt++]=tem;
                    }
                    else break;
                }
                enter(op,*str);
                str++;break;
            default :
                ho[cnt++]=*str;
                str++;break;


        }
    }
    while(!empt(op))
    {
        out(op,tem);
        ho[cnt++]=tem;
    }
    ho[cnt]='\0';
    destory(op);
}

int main()
{
    scanf("%s",str);
    trans(str,ho);
    printf("%s",ho);
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值