数据结构实验之栈与队列二:一般算术表达式转换成后缀式

Problem Description

对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。

Input

输入一个算术表达式,以‘#’字符作为结束标志。

Output

输出该表达式转换所得到的后缀式。

Sample Input

a*b+(c-d/e)*f#

Sample Output

ab*cde/-f*+

Hint

 

Source

 

#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 100
#define ERROR -9999999
typedef struct
{
    char num[MAXSIZE];
    int top;
}SeqStack;

void InitSeqStack(SeqStack* s)
{
    s->top = -1;
}

int IsEmpty(SeqStack *s)
{
    if (s->top == -1)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

char Pop(SeqStack *s)
{
    if(!IsEmpty(s))
    {
        return s->num[s->top--];
    }
    return ;
}

void Push(SeqStack *s, char ch)
{
    if (s->top >= MAXSIZE-1)
    {
        return ERROR;
    }
    s->top++;
    s->num[s->top] = ch;
}

char GetTop(SeqStack *s)
{
    return s->num[s->top];
}

int Priority(char ch)  // 判断符号优先级
{
    int ret = 0;
    switch (ch)
    {
    case '+':
    case '-':
        ret = 1;
        break;
    case '*':
    case '/':
        ret = 2;
        break;
    }
    return ret;
}

int main()
{
    SeqStack s;
    char ch;
    InitSeqStack(&s);
    ch = getchar();
    while(ch != '#')
    {
        if(ch >= 'a' && ch <= 'z')  // 若为字母,则直接输出
        {
            printf("%c", ch);
        }
        else if ((ch == '+'||ch == '*'||
                 ch == '/'||ch == '-'))  // 若为运算符,则进行优先级比较
        {
            while(!IsEmpty(&s)&&(Priority(ch) <= Priority(GetTop(&s))))
            {
                printf("%c", Pop(&s));
            }
            // 若栈不为空,且进来的符号优先级小于等于栈顶元素
            // 则弹出栈顶元素,直到栈顶元素优先级小于新元素
            // 或栈弹空
            Push(&s, ch);
        }
        else if (ch == '(')
        {
            Push(&s, ch);
        }
        else if (ch == ')')
        {
            while(GetTop(&s) != '(')
            {
                printf("%c", Pop(&s));
            }
            // 弹出左括号前所有元素
            Pop(&s); // 弹出左括号,但不输出
        }
        ch = getchar();
    }
    while(!IsEmpty(&s))  // 将栈中剩余元素弹出
    {
        printf("%c", Pop(&s));
    }
    return 0;
}

 

原文地址:https://www.cnblogs.com/sugerandmaster/p/11529919.html