【问题标题】:Stack Data structures (infix to postfix)堆栈数据结构(后缀的中缀)
【发布时间】:2021-10-02 02:12:00
【问题描述】:

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

#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-structures stack


【解决方案1】:

条件

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

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

两者都不同。

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

【讨论】:

    猜你喜欢
    • 2018-10-02
    • 2020-10-09
    • 2013-02-26
    • 2013-03-28
    • 1970-01-01
    • 2015-05-22
    • 2015-05-09
    • 2015-09-12
    • 2012-04-05
    相关资源
    最近更新 更多