2020.3.28关于中序算法转后序(不含括号)的初步思路与代码

本文介绍了一种将中序表达式转换为后序表达式的算法实现,通过使用栈来辅助处理运算符的优先级,实现了基本的非括号运算转化。代码示例展示了如何用C语言实现这一转换过程。

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

把中序算法转化为后序算法的初步思路
代码如下:

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

struct list
{
    char fu[10];
    int top;
};
struct list* Creat()
{
    struct list* p;
    p=(struct list *)malloc(sizeof(struct list));
    p->top=-1;
    return p;
}

void pop(struct list *head,char p){
    head->fu[++head->top]=p;
}
void  push(struct list *head,char*p2){
    *p2=head->fu[head->top--];
}
int  ad(struct list *head,char p,char*p2)//判断字符的操作
{
    if(head->top!=-1)
    {
        if(p=='+'||p=='-')
        {
            push(head,p2);
            return 1;
        }
        if(p=='*'||p=='/'||p=='%')
        {
            if(head->fu[head->top]=='*'||head->fu[head->top]=='/'||head->fu[head->top]=='%'){
                push(head,p2);
                return 1;
            }
            pop(head,p);
            return 0;
        }
       /* if(p=='(')
        {
            pop(head,p);
        }
        if(p==')')
        {
            while(head->fu[head->top]!='('){
                push(head,p2);
                p2++;
                ad(head,p,p2);
            }
            push(head,p2);
            p2++;
            ad(head,p,p2);
        }*/
    }
    if(head->top==-1)
        pop(head,p);
    return 0;
}

void print(struct list* head,char *p,char*p2)//判断是否是字符的操作
{
    int i1=0;
    while(p[i1])
    {
        if(p[i1]!='+'&&p[i1]!='-'&&p[i1]!='*'&&p[i1]!='/'&&p[i1]!='('&&p[i1]!=')')
        {
            *p2=p[i1];
            p2++;
        }
        else{
            while(ad(head,p[i1],p2))//在print中 进行字符数组地址前进,每一次操作,必定返回print函数 若要持续进行操作。必须每次返回print
                p2++;
                  }
        i1++;
    }
        push(head,p2);
}

int main()
{
    struct list*head;
    char zhong[20],hou[20];
    head=Creat();
    gets(zhong);
    print(head,&zhong[0],&hou[0]);
    puts(hou);
    return 0;
}

流程如下。输入一串字符,进行初步判断,若不为符号,则直接输出,若遇到符号,入栈(此时符号栈为空,不需要判断符号的先后),当符号栈为非空时,进行符号入栈需要进行判断,暂时只能进行非括号的运算转化,有括号出现乱码,代改进

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值