The shortest way to convert infix expressions to postfix (RPN) in C

后端 未结 3 1848
一个人的身影
一个人的身影 2021-02-13 12:35

Original formulation is given here (you can try also your program for correctness) .

Additional rules:
1. The program should read from standard input and write to s

相关标签:
3条回答
  • 2021-02-13 13:19

    Here's a way to reduce the code down to 76 chars:

    main(c){read(0,&c,1)?c-41&&main(c-40&&putchar(c,c%96>26&&main(c))):exit(0);}
    

    A longer, commented version for clarity:

    int main(int c)
    {
       if (read(0,&c,1)) {          /* read char */
           if (c-41) {              /* if not ')' */
               if (c-40) {          /* then if not '(' */
                   if (c%96>26) {   /* then if operator (not alphabet or <LF>) */
                       main(c);     /* recurse */
                   }
                   putchar(c);      /* print */
               }
               main(c);             /* recurse */
           }        
       } else exit(0);              /* end program */
    }
    
    0 讨论(0)
  • 2021-02-13 13:28

    I'm not out to break any records but I'll post this anyway:

    #define x(z) while(p>##z s)putchar(*p--);
    main(c){
    int s[9],*p=s-1;
    for(;read(0,&c,1);){
    isalpha(c)?putchar(c):c=='('?(c=0):c==')'?(c=1):isdigit(c)?:(*++p=c);
    if(c==0){x()main(0);}
    if(c==1) break;}
    x(=)return 0;}
    

    Edit: Fixed correctness issues pointed out by kuszi's comment.

    0 讨论(0)
  • 2021-02-13 13:34

    Well, the real winner is the one who wrote this small code you provided, but you can slightly modify it to remove the exit:

    main(c){read(0,&c,1)?c-41&&main(c-40&&(c%96<27||main(c),putchar(c))):0;}
    

    I tried and it works.

    0 讨论(0)
提交回复
热议问题