【C语言】中缀表达式转后缀表达式

#include 
#include 
#include 
#define MAXSIZE 20

typedef struct
{
    int data[MAXSIZE];
    int top;
} Stack;

void InitStack(Stack *S)
{
    S->top = 0;
}
void push(Stack *S, int e)
{
    if (S->top == MAXSIZE)
        return;
    S->data[S->top++] = e;
}
void pop(Stack *S, int *e)
{
    if (S->top == 0)
        return;
    *e = S->data[--S->top];
}
int GetTopElem(Stack S)
{
    return S.top == 0 ? -1 : S.data[S.top - 1];
}
int IsEmpty(Stack S)
{
    return S.top == 0;
}
void PrefixToRevPolish(char prefix[], int prelen, char revpolish[])
{
    Stack s;
    InitStack(&s);
    int pos = 0;
    int elem;
    for (int i = 0; i < prelen; i++)
    {
        if (prefix[i] >= '0' && prefix[i] <= '0' + 9 || prefix[i] >= 'A' && prefix[i] <= 'Z')
        {
            revpolish[pos] = prefix[i];
            pos++;
        }
        else if (prefix[i] == '(')
        {
            push(&s, '(');
        }
        else if (prefix[i] == ')')
        {
            while ('(' != GetTopElem(s) && (!IsEmpty(s)))
            {
                pop(&s, &elem);
                revpolish[pos] = elem;
                pos++;
            }
            if ('(' == GetTopElem(s))
                pop(&s, &elem);
        }
        else
        {
            switch (prefix[i])
            {
            case '+':
            case '-':
            {
                while (('(' != GetTopElem(s)) && (!IsEmpty(s)))
                {
                    pop(&s, &elem);
                    revpolish[pos] = elem;
                    pos++;
                }
                if ('(' == GetTopElem(s))
                    pop(&s, &elem);
                push(&s, prefix[i]);
                break;
            }
            case '/':
            case '*':
            {
                while (('(' != GetTopElem(s)) && (!IsEmpty(s)))
                {
                    if ('/' == GetTopElem(s) || '*' == GetTopElem(s))
                    {
                        pop(&s, &elem);
                        revpolish[pos] = elem;
                        pos++;
                    }
                    else
                    {
                        push(&s, prefix[i]);
                        break;
                    }
                }
                if ('(' == GetTopElem(s))
                    pop(&s, &elem);
                if (IsEmpty(s))
                    push(&s, prefix[i]);
                break;
            } // case '/*'
            } // switch

        } // else
    }     // for
    while (!IsEmpty(s))
    {
        pop(&s, &elem);
        revpolish[pos++] = elem;
    }
    revpolish[pos] = '\0';
}
int main()
{

    char prefix[] = {"A*B/C-D"}; // 测试用例:9+(1+7)+1*3+1/5-4
    char revpolish[MAXSIZE] = {0};
    int prelen = sizeof(prefix) / sizeof(prefix[0]);

    PrefixToRevPolish(prefix, prelen, revpolish);

    printf("中缀表达式为:%s\n后缀表达式为: %s\n", prefix, revpolish);

    system("pause");
    return 0;
}

你可能感兴趣的:(c语言,开发语言)