簡體   English   中英

在C中使用堆棧的中綴到Postfix <incorrect output after a '(' is inserted in the expression>

[英]Infix to Postfix using stack in C <incorrect output after a '(' is inserted in the expression>

#include<stdio.h>
#include<stdlib.h>
#define MAX 100

typedef struct 
{
    char data[MAX];
    int top;
}stack;

void push(stack*,char);
char pop(stack*);
int empty(stack*);
int priority(char);
char top(stack*);

int main(int argc,char* argv[])
{
    stack s;
    char ch,token,temp,temp1;
    int k=0;
    char infix[MAX];
    s.top=-1;

    printf("\nInput an infix expression.\n");
    scanf("%s",infix);
    while((ch=infix[k++])!='\0')
    {
        if(isalnum(ch)) // checks if character is alphanumeric
            printf("%c",ch);
        else if(ch=='(') // if '(' push to stack
            push(&s,ch);
        else if(ch==')')  // if ')' pop all elements till a '(' is encountered 
            while(token=pop(&s)!='(')
            {
                printf("%c",token);
            }
        else
        {
            // if character is an operator
            while(!empty(&s) && priority(ch)<=priority(top(&s))) 
            {
                token=pop(&s);
                printf("%c",token);
            }
            push(&s,ch);
        }
    }

    if(!empty(&s)) // prints the remaining characters in the stack
    {
        token=pop(&s);
        printf("%c",token);
    }

    return 0;
}

void push(stack* s,char ch)
{
    if(s->top==-1)
        s->top=0;
    else
        s->top=s->top+1;
    s->data[s->top]=ch;
}

char pop(stack* s)
{
    char ch;
    ch=s->data[s->top];
    s->top=s->top-1;
    return ch;
}

int empty(stack* s)
{
    if(s->top==-1)
        return 1;
    return 0;
}

int priority(char ch)
{
    if(ch=='(')
        return 1;
    else if(ch=='+' || ch=='-')
        return 2;
    else if(ch=='*' || ch=='/' || ch=='%')
        return 3;
}

char top(stack* s)
{
    return (s->data[s->top]);
}

OUTPUT

輸入中綴表達式。

(A + B)* C /(A + B * C)

ab☺c*abc☺☺/

輸入中綴表達式。

一個+ BC / d

AB + CD /

當插入'('時,程序會顯示無效字符。非常感謝您的幫助。

優先級。 賦值運算符的優先級非常低,所以

while(token=pop(&s)!='(')

表現如下:

while (token = (pop(&s)!='(') )

並且令牌僅分配1或0,具體取決於比較結果。 你要:

while ((token=pop(&s)) != '(')
if(isalnum(ch))

如果使用isalnum則應該#include <ctype.h>

while(token=pop(&s)!='(')

比較運算符優先於賦值運算符,這意味着你在這里比較pop(&s)!='('然后將結果( 01 )分配給token 。比較仍然有效,循環行為正確,但token的字符將是一些控制字符,而不是字母。

使用正確的括號:

while((token=pop(&s))!='(')

您的函數int priority(char ch)沒有針對每個可能的輸入的return語句。 你應該添加一個最終的return語句來捕獲這些情況(即使它們不應該發生)

你的大部分代碼也很冗長,沒有必要。 例如:

char pop(stack* s)
{
    char ch;
    ch=s->data[s->top];
    s->top=s->top-1;
    return ch;
}

是相同的:

char pop(stack* s)
{
    s->top--;
    return s->data[s->top+1];
}

要么

int empty(stack* s)
{
    if(s->top==-1)
        return 1;
    return 0;
}

是相同的

int empty(stack* s)
{
    return s->top == -1;
}

暫無
暫無

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

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