C 中的后缀到中缀的转换

问题描述 投票:0回答:1

任何人都可以帮助我在 C 中将 Postfix 转换为 Infix,我尝试了几次但仍然无法弄清楚逻辑。

我知道算法,它是这样的:

  • 将表达式作为输入
  • 如果 char 是操作数,则将其压入堆栈
  • 如果char是运算符,则连续从栈中弹出两个元素,将运算符放在它们之间,然后将结果表达式压入栈
  • 做上面的步骤直到没有读出整个表达式
#include<stdio.h>

char st[100];
int top = -1;

void push(char el)
{
  st[++top] = el; 
}

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

int isop(char val)
{
  if (val == '+' || val == '-' || val == '*' || val == '/' || val == '%')
  {
    return 1;
  } else {
    return 0;
  }
}
void main()
{
  char exp[50], v1, v2, ex;
  int i = 0;

  printf("Enter the expression: ");
  gets(exp);

  while(exp[i] != '\0')
  {
    if(isop(exp[i]))
    {
      v1 = pop();
      v2 = pop();
      ex = exp[i];

    } else {
      push(exp[i]);
    }
    i++;
  }
}

我唯一卡住的地方是,我如何将结果表达式(通过将运算符放在两个弹出的操作数之间获得的表达式)再次压入堆栈。

谢谢。

c data-structures stack postfix-notation
1个回答
0
投票
#include<stdio.h>
#include<stdlib.h>
struct node *createNode();
void push(struct node *);
struct node *pop();
void infixConvert(char []);
void display(struct node *);
struct node {
    char ch;
    struct node *left;
    struct node *right;
}*stack[11];
int top=11;
void main() {
    char expr[25];
    printf("Enter the Expression : ");
    scanf("%s",expr);
    infixConvert(expr);
    printf("Infix Expression : ");
    display(pop(top));
}
struct node *createNode() {
    struct node *newnode;
    newnode=(struct node*)malloc(sizeof(struct node));
    return newnode;
}
void infixConvert(char expr[]) {
    struct node *op1, *op2;
    struct node *newnode;
    int i;
    for(i=0;expr[i]!='\0';i++) {
        if(expr[i]>='a'&&expr[i]<='z'||expr[i]>='A'&&expr[i]<='Z') {
            newnode=createNode();
            newnode->ch=expr[i];
            newnode->left=NULL;
            newnode->right=NULL;
            push(newnode);
        }
        else if(expr[i]=='+'||expr[i]=='-'||expr[i]=='*'||expr[i]=='/'||expr[i]=='^') {
            op1=pop();
            op2=pop();
            newnode=createNode();
            newnode->ch=expr[i];
            newnode->right=op1;
            newnode->left=op2;
            push(newnode);
        }
    }
}
void push(struct node *ch) {
    if(top<=0) {
        printf("Full Stack");
        return;
    }
    stack[top]=ch;
    top--;
}
struct node *pop() {
    if(top>=11) {
        printf("Stack Empty");
    }
    else {
        return stack[++top];
    }
}
void display(struct node *temp) {
    if(temp==NULL) {
        return;
    }
    display(temp->left);
    printf("%c",temp->ch);
    display(temp->right);
}
© www.soinside.com 2019 - 2024. All rights reserved.