簡體   English   中英

使用堆棧的后綴轉換的中綴

[英]infix to postfix conersion using stack

我編寫了將后綴符號轉換為后綴1的代碼。 它不用括號就可以正常工作,但是當我將表達式用括號括起來時,卻給了我運行時錯誤。 我必須使用命令行參數。

#include<stdio.h>
int top = -1;
push(char *s, char elem) {
  ++top;
  s[top] = elem;
}

char pop(char *s) { 
 char elem;
  elem = s[top];
  top--;
  return (elem);
 }

int Sempty() { 
 if (top == -1)
  return 1;
 return 0;
}

int pri(char elem){
switch(elem){
case '/':
case '*':   return 2;
case '+':
case '-':   return 1;
}   }

main(int argc, char *argv[]){
int i, x, y;
char elem, new;
char a[50];
printf("\t\t------infix notation-----\n");
for(i = 1; i<argc; i++) printf("%s ", argv[i]);
printf("\n\t\t------postfix notation-----\n");
for(i = 1; i<argc; i++){
if(argv[i][0] == '(')   push(a, argv[i][0]);
else if(isalnum(argv[i][0]))    printf("%s ", argv[i]);
else if(argv[i][0] == ')'){ elem = pop(a);
    while(elem != '('){
        printf("%c ", elem);
        elem = pop(a);  }
    if(elem == '(') top--;
        }
else{
x = pri(argv[i][0]);
    if(Sempty())    push(a, argv[i][0]);
    else{
    elem = pop(a);
    y = pri(elem);
        if(y>=x){
            printf("%c ", elem);
            push(a, argv[i][0]);    }
        else{ 
            push(a, elem);  
            push(a, argv[i][0]);}
        }   }
}
while(!Sempty()){
elem = pop(a);
printf("%c ", elem);    }
printf("\n");
}

輸入

./a.out 2 + 3

產量

------infix notation-----
2 + 3 

------postfix notation-----

2 3 + 

但是如果我給

輸入

./a.out ( 2 + 3 )

產量

bash: syntax error near unexpected token `2'

括號對外殼有特殊含義,您必須引用或轉義它們:

./a.out '(' 2 + 3 ')'

暫無
暫無

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

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