1

我正在尝试实现中缀到后缀转换的代码,但我无法获得输出。通过分析程序,我发现变量 top 没有得到更新,即使我将它的值返回给 main。请帮我弄清楚。代码是:

#include<stdio.h>

char stack[15];

int check(char op)
{
     int rank=0;

         switch(op)
      {
          case '/': 
                    rank=1;
                    break;
          case '*':
                    rank=2;
                    break;
          case '+':
                    rank=3;
                    break;
          case '-':
                    rank=4;
                    break;                    
      }
      return rank;
}


int POP(char stack[15],int top)
{
    if(top==-1)
    {
         printf("Stack Underflow");
         return top;
    }
    else
    {
        top--;
        printf("%c",stack[top+1]);
        return top;
    }
}



int PUSH(char stack[15],int top,char op)
 {
      char opstack;
      int rank1,rank2;
 if(top>=14)
     {
        printf("Stack Overflow");
        return top;
     }

     else
     {
        if(top==-1)
        {
            top++;
            stack[top]=op;
            return top;
        }

        else
        {
           opstack=stack[top];
           rank1=check(op);
           rank2=check(opstack);    

           if( rank1 <= rank2 )
           {
              top++;
              stack[top]=op;
           }
         else
         {
          top=POP(stack,top);

          top=PUSH(stack,top,op);
         }
             return top;
       }

    }
 }


int main()
{
char string[15],ch;
int top=-1,i;

printf("Enter the infix operation: ");
gets(string);
fflush(stdin);
for(i=0;string[i]!='\0';i++)
{
     ch=string[i];
     if( ((ch>='a') && (ch<='z'))||((ch>='A') &&(ch<='Z')) )
     {
      printf("%c",string[i]);
     }
     else
     {
         ch=string[i];
     top=PUSH(stack,top,ch);
 }
     top=POP(stack,top);
}
return 0; 
} 
4

1 回答 1

1

在主函数中,在 for 循环结束后添加这三行。并在 for 循环中删除 top=POP(stack,top);

 while(top!=-1)
 top=POP(stack,top);
 printf("\n");

修改主函数:

int main()
{
char string[15],ch;
int top=-1,i;

printf("Enter the infix operation: ");
gets(string);
fflush(stdin);
for(i=0;string[i]!='\0';i++)
{
     ch=string[i];
     if( ((ch>='a') && (ch<='z'))||((ch>='A') &&(ch<='Z')) )
     {
      printf("%c",string[i]);
     }
     else
     {
     ch=string[i];
     top=PUSH(stack,top,ch);
     }

}
     while(top!=-1)
     top=POP(stack,top);
     printf("\n");
   return 0;
}
于 2013-09-02T12:46:29.447 回答