簡體   English   中英

中綴到后綴循環

[英]Infix to postfix Looping

在此處輸入代碼,

#include <stdio.h>
#include <ctype.h>

#define SIZE 50
char s[SIZE];
int top=-1;   

void push(char elem)
{                  
    s[++top]=elem;
}

char pop()
{                     
    return(s[top--]);  
}

int pr(char elem)
{                
    switch(elem)
    {
        case '#': return 0;
        case '(': return 1;
        case '+':
        case '-': return 2;
        case '*':
        case '/': return 3;
    }
}

void main()
{                       
    char infx[50],pofx[50],ch,elem;
    int i=0,k=0,j;
    for(j=0;j<=3;j++)
    {
        printf("\n\nRead the Infix Expression ? ");
        scanf("%s",infx);
        push('#');
        while( (ch=infx[i++]) != '\0')
        {
            if( ch == '(') 
                push(ch);
            else
                if(isalnum(ch)) 
                    pofx[k++]=ch;
                else
                    if( ch == ')')
                    {
                        while( s[top] != '(')
                        pofx[k++]=pop();
                        elem=pop();
                    }
                    else
                    {      
                        while( pr(s[top]) >= pr(ch) )
                            pofx[k++]=pop();
                        push(ch);
                    }
        }  

        while( s[top] != '#')    
            pofx[k++]=pop();

        pofx[k]='\0';         
        printf("\n\nGiven Infix Expn: %s  Postfix Expn: %s\n",infx,pofx);
    }
}

當循環中綴到后修復表達式時,它不會循環超過第一個循環。

它正在生成第一個循環的輸出並顯示其余循環的分段錯誤

請問有人可以指導我嗎?

考慮一個例子

給定輸入,

給定中綴擴展:a+b 后綴擴展:ab+

閱讀中綴表達式? AB
分段錯誤(核心轉儲)

您需要為每個新輸入重置pofxinfx的索引。 即在for-loop重置ik 修復如下,

void main()
{                       
    char infx[50],pofx[50],ch,elem;
    int i=0,k=0,j;
    for(j=0;j<=3;j++)
    {
        i=0;j=0;//here is the update

        //rest of your code follows,

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM