zoukankan      html  css  js  c++  java
  • 中缀 转 后缀

    #include <cstdio>
    #include <cstdlib>
    //#define _OJ_
    #define maxsize 100
    typedef struct stack1
    {
        char *elem;
        int top;
        int base;
    } stack1, *stack;


    stack
    creat_stack(void)
    {
        stack s;
        s = (stack) malloc (sizeof(stack1));
        s->elem = (char*) malloc (maxsize * sizeof(char));
        s->top = s->base = 0;
        return s;
    }

    char
    pop(stack s)
    {
        return s->elem[--s->top];
    }

    void
    push(stack s, char ch)
    {
        s->elem[s->top++] = ch;
    }

    int
    isempty(stack s)
    {
        if(s->top == s->base)
            return 1;
        else
            return 0;
    }

    char
    gettop(stack s)
    {
        return s->elem[s->top - 1];
    }

    int
    getrank(char ch)
    {
        switch (ch) {
        case '+':
        case '-':return 1;break;
        case '*':
        case '/':return 2;break;
        case '(':return 3;break;
        default :return 100;
        }
    }


    int main(int argc, char const *argv[]) {
    #ifndef _OJ_  //ONLINE_JUDGE
        freopen("input.txt", "r", stdin);
    #endif
        char ch1;
        int n1, n2;
        int i = 0;
        stack s;
        char  str[100];


        while (scanf("%s", str) != EOF) {
        if(str[1] == '')    continue;
        s = creat_stack();
        i = 0;
        while (str[i] != '') {
          if('0' <= str[i] && str[i] <= '9')
            printf("%c", str[i]);

          else if(str[i] == '(')
            push(s,str[i]);

            else if(str[i] == ')')
                {
                while(gettop(s) != '(')
                printf("%c", pop(s));
                pop(s);
                }
            else
            {
             if(isempty(s))    push(s,str[i]);
             else{
             ch1 = gettop(s);//printf("ch1 == %c ", ch1);
             n1  = getrank(str[i]);//printf("n1 == %d ", n1);
             n2  = getrank(ch1);//printf("n2 == %d ", n2);
             while((ch1 != '(') && (isempty(s) != 1) && (n1 <= n2)) {
                printf("%c", pop(s));    if(isempty(s))    break;
                ch1 = gettop(s);
                n2  = getrank(ch1);
            }
            push(s,str[i]);
            }
             // printf("top == %c ", gettop(s));
            //printf("rank == %d ", getrank(str[i]));
            //printf("%c ", str[i]);
            }

            i++;
        }


        while (!isempty(s))
          printf("%c", pop(s));
          printf(" ");

    }

        return 0;
    }


    /*12+
    12+3*45*+*/

  • 相关阅读:
    关于TxQBService报的错,腾讯你真牛B啊
    用C#读取txt文件的方法
    Python-Redis的发布与订阅
    Python-连接Redis并操作
    Python-Redis的Set操作
    Python-Redis的List操作
    Python-Redis的Hash操作
    Python-Redis的String操作
    Python-RabbitMQ消息队列实现rpc
    Python-RabbitMQ消息队列的发布与订阅
  • 原文地址:https://www.cnblogs.com/airfand/p/4993173.html
Copyright © 2011-2022 走看看