首页 > 解决方案 > 堆栈数据结构(后缀的中缀)

问题描述

这是一个将堆栈数据结构中的中缀转换为后缀的程序。

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int F(char symbol)

{

switch(symbol)

{

case '+':

case '-':return 2;

case '*':

case '/':return 4;

case '^':

case '$':return 5;

case '(':return 0;

case '#':return -1;

default:return 8;

}

}

int G(char symbol)

{

switch(symbol)

{

case '+':

case '-':return 1;

case '*':

case '/':return 3;

case '^':

case '$':return 6;

case '(':return 9;

case ')':return 0;

default:return 7;

}

}

void infixtopostfix(char infix[],char postfix[])

{

int top,i,j=0;

top = -1;

char s[30],symbol;

s[++top]= '#';

for(i=0;i<strlen(infix);i++)

{

symbol = infix[i];

while(F(s[top]) > G(symbol))

{

postfix[j]=s[top--];

j++;

}

if(F(s[top]) != G(symbol))

s[++top]=symbol;

else

top--;

}

while(s[top] != '#')

{

postfix[j++]=s[top--];

}

postfix[j] = '\0';

}

int main()

{

char infix[20],postfix[20];

printf("Enter the infix expression:\n");

scanf("%s",infix);

infixtopostfix(infix,postfix);

printf("Postfix Expression is %s",postfix);

return 0;

}

在这段代码中,以下几行发生了什么?

if(F(s[top]) != G(symbol))

s[++top]=symbol;

else

top--;

}

while(s[top] != '#')

{

postfix[j++]=s[top--];

}

我不明白 f(s[top]) != g(symbol) 与 f(s[top]) > g(symbol) 有何不同,因为如果它更大,则自动意味着它不相等。f(s[top]) 和 g(symbol) 是什么?

标签: data-structuresstack

解决方案


条件

f(s[top]) != g(symbol)

f(s[top]) > g(symbol)

两者都不同。

如果 f(s[top]) 和 g(symbol) 相等,第一个给出 false。但是在第二种情况下,如果 f(s[top]) 小于 g(symbol),那么它会生成 false。但是根据第一个条件,应该生成true。


推荐阅读