我需要帮助才能在C中从中缀转换为后缀

问题描述 投票:2回答:1

我正在练习一些我以前做过的数据结构问题,但这次我不知道我的代码出了什么问题。我看了很久但没有发现错误。当我打印时,我只是获得第一个字符,看起来e没有被更新。但我写了e ++。

#include<stdio.h>
#include "ctype.h"
int stack[20];
int top = -1;

void push(int x)
{
    stack[++top] = x;
}

int pop()
{
    return stack[top--];
}
int priorityof(char x)
{
    if(x=='(')
        return 3;
    else if(x=='+'|| x=='-')
        return 1;
    else if(x=='*'|| x=='/')
        return 2;
}

int main()
{
    char exp[20];
    char *e;
    e=exp;char x;
    scanf("%c",exp);
    while(*e!='\0')
    {
        if(isalnum(*e))
        {
            printf("%c", *e);
        }
        else if(*e=='(')
        {
            push(*e);
        }
        else if(*e==')')
        {
            while((x=pop())!='(')
                printf("%c",x);
        }
        else {
            while (priorityof(stack[top]) >= priorityof(*e)) {
                printf("%c", pop());
                push(*e);
            }

        }
        e++;
    }
    while(top!=-1)
    {
        printf("%c",pop());
    }
}
c data-structures stack postfix-notation infix-notation
1个回答
1
投票

%c用于单个字符并且阅读你的问题,看起来你提供的不止一个字符所以它是一个字符串,使用%s


#include<stdio.h>
 #include "ctype.h" 
int stack[20]; int top = -1;
 void push(int x) { 
stack[++top] = x;
 } 
int pop() { return stack[top--]; } 
int priorityof(char x) {
 if(x=='(') return 3;
 else if(x=='+'|| x=='-') return 1;
 else if(x=='*'|| x=='/') return 2;
 } 
int main() { 
char exp[20]; 
char *e; 
e=exp;char x; 
scanf("%s",exp); 
while(*e!='\0') { if(isalnum(*e)) { printf("%c", *e); } else if(*e=='(') { push(*e); } else if(*e==')') { while((x=pop())!='(') printf("%c",x); } else { while (priorityof(stack[top]) >= priorityof(*e)) { printf("%c", pop()); push(*e); } } e++; } while(top!=-1) { printf("%c",pop()); } }

© www.soinside.com 2019 - 2024. All rights reserved.