簡體   English   中英

使用數組堆棧將后綴轉換為中綴表示法

[英]Converting postfix to infix notation using array stack

我正在嘗試編寫一個將后綴轉換為中綴表示法的程序,但這對我來說並不容易。

pfix  stack          explanation (@ is space)  
---------------------------------------------  
3     3  
4     3 4  
5     3 4 5  
+     3 (4@+@5)      if exp[i] is op, do some action  
*     (3@*@(4@+@5))  if exp[i] is op, do some action  

一些動作意味着它從堆棧中彈出兩次,插入“空格+運算符+空格”,並用括號將其包裹起來。 然后將其壓入堆棧。

但是當我執行這個程序時,它根本不起作用。

cygwin_exception::open_stackdumpfile:將堆棧跟蹤轉儲到 post2in.exe.stackdump

我怎樣才能解決這個問題?

謝謝。

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define M 20
#define N 20

char stk[M][N];  // array of string
int top = -1;

void push(char (*)[N], char *);
char *pop(char (*)[N]);
void getexp(char *);
int isop(char);

int main() {
  char *exp = "abc+*";
  getexp(exp);
  printf("%s ", *stk[0]);
  return 0;
}

void getexp(char *exp) {
  while (*exp = '\0') {

    /* if space or tab, skip */
    if (*exp == ' ' || *exp == '\t') exp++;

    /* if digit or point, get whole number and store it into array stack */
    else if (isdigit(*exp) || *exp == '.') {
      char digits[20];
      int i = 0;
      while (*exp != ' ' && *exp != '\0') {
        digits[i++] = *exp++;
      }
      digits[i] = '\0';
      push(stk, digits);
    }

    /* if operator, pop twice and wrap them with parenthesis with operator */
    else if (isop(*exp)) {
      char bwparens[20], pop1[20], pop2[20], temp[4];
      strcpy(pop2, pop(stk));
      strcpy(pop1, pop(stk));
      temp[0] = ' ';
      temp[1] = *exp;
      temp[2] = ' ';
      temp[3] = '\0';
      bwparens[0] = '(';
      strcat(strcat(strcat(bwparens, pop1), temp), ")\0");
      push(stk, bwparens);
      exp++;
    }
  }
}

int isop(char chr) {
  return (chr == '+' || chr == '-' || chr == '*' || chr == '/' || chr == '%');
}

void push(char stk[M][N], char *exp) {
  if (top == -1) {
    printf("Stack is full");
    exit(EXIT_FAILURE);
  } else
    strcpy(stk[++top], exp);
}

char *pop(char stk[M][N]) {
  if (top == -1) {
    printf("Stack is empty.\n");
    exit(EXIT_FAILURE);
  } else {
    return stk[top--];
  }
}

您將 exp 設置為始終等於 null 終止,這會導致無限循環:

while (*exp = '\0')

我認為這可能是問題之一。

我希望這個對你有用。

暫無
暫無

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

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