zoukankan      html  css  js  c++  java
  • 数据结构:中缀表达式转后缀表达式

    #include <stdio.h>
    #include "SqStack2.h"
    #define STACKTYPE SqStack
    
    #define BOOL int
    #define TRUE 1
    #define FALSE 0
    
    BOOL isnumeric(char c)
    {
        return (c >= '0' && c <= '9') ? TRUE : FALSE;
    }
    
    int lv(char c)
    {
        int wt[] = {3,0,2,1,-1,1,-1,2};
        return wt[c - '('];
    }
    
    void expr()
    {
        char ex[] = "10+(3+4)*(12-6)";
        int i,n;
        BOOL isNumber = FALSE;//上一个字符是否是数字,连续两个数字要合并
        STACKTYPE st;
        init(&st);
        for (i = 0; ex[i] != ''; i++) {
            if (isnumeric(ex[i])){
                if (isNumber == FALSE) printf(" ");
                printf("%d", ex[i]-'0');
                isNumber = TRUE;
            }
            else {
                isNumber = FALSE;
                if (ex[i] == ')'){//如果是右括号,则匹配栈中第一个左括号
                    n = ' ';
                    do {
                        if (n != ' ') printf(" %c", n);
                    } while (pop(&st, &n)==OK && n != '(');
                }
                else if (ex[i] == '(') {//左括号直接入栈
                    push(&st, ex[i]);
                }
                else {//其他运算符,输出栈中所有优先度更高的运算符
                    while (getTop(st, &n) == OK && n != '(' && lv(n) >= lv(ex[i]))
                        pop(&st, &n);
                    push(&st, ex[i]);
                }
            }
        }
    
        while (pop(&st, &n) == OK)
            printf(" %c", n);
    
        printf("
    ");
        destroy(&st);
    }
    
    main()
    {
        expr();
    }
  • 相关阅读:
    搞懂树状数组
    C#接口(Interface)
    C#接口(Interface)
    C#运算符的重载
    C#和C++的区别(一)
    hdu1874 畅通工程续
    hdu1874 畅通工程续
    C#多态性
    C#多态性
    C#继承
  • 原文地址:https://www.cnblogs.com/ifan/p/4227623.html
Copyright © 2011-2022 走看看