中缀表达式转换为后缀表达式(C语言实现)

逆波兰计算器 中缀表达式转换为后缀表达式(C语言实现)

逆波兰表达式是一种把运算符前置的算术表达式,例如普通的表达式2 + 3的逆波兰表示法为2 3 +。逆波兰表达式的优点是运算符之间不必有优先级关系,也不必用括号改变运算次序,例如(2 + 3) * 4的逆波兰表示法为*2 3 + 4 *。其中运算符包括+ - * /四个

我之前的博客写了一个逆波兰算法1.0是输入后缀表达式时候的逆波兰计算器,这篇博客主要是将输入的中缀表达式转化为后缀表达式,加入将两个博客的代码结合,就可以实现输入咱们普通的中缀表达式,然后以逆波兰计算器的方式输出结果

虽然好像没什么意义,哈哈哈哈。

老规矩 咱们话不多说上代码!!

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

# define STACK_INIT_SIZE 20
# define STACKINCREMENT 10
# define MAXBUFFER 10

typedef char ElemType;
typedef struct
{
    ElemType *base;
    ElemType *top;
    int stackSize;
}sqstack;


void Initstack(sqstack *s)
{
    s->base =(ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));
    if(!s->base)
    {
        exit(0);
    }
    s->top=s->base;
    s->stackSize=STACK_INIT_SIZE;
}

void push(sqstack *s,ElemType e)
{
    if(s->top-s->base>=s->stackSize)    //栈满,增加栈的size
    {
        s->base=(ElemType *)realloc(s->base,(s->stackSize+STACKINCREMENT)*sizeof(ElemType));
        if(!s->base)
        {
            exit(0);   	//表示空间分配失败,用exit函数跳出。
        }
    }
    *(s->top)=e;
    s->top++;
}

void Pop(sqstack *s,ElemType *e)
{
    if(s->top==s->base)
    {
        return;
    }
    *e=*--(s->top);
}

int StackLen(sqstack s)
{
    return (s.top-s.base);
}
int main()
{
    sqstack s;
    char c,e;
    Initstack(&s);
    printf("请输入中缀表达式,以#作为结束标志:");
    scanf("%c",&c);
    while(c!='#')
    {
        while(c>='0'&&c<='9')
        {
            printf("%c",c);
            scanf("%c",&c);
            if(c<'0'||c>'9')
            {
                printf(" ");
            }
        }
        if(')'==c)
        {
            Pop(&s,&e);
            while('('!=e)
            {
                printf("%c ",e);
                Pop(&s,&e);
            }
        }
        else if('+'==c||'-'==c)
        {
            if(!StackLen(s))
            {
                push(&s,c);
            }
            else
            {
                do
                {
                    Pop(&s,&e);
                    if('('==e)
                    {
                        push(&s,e);
                    }
                    else
                    {
                        printf("%c ",e);
                    }
                }while(StackLen(s)&&'('!=e);
                push(&s,c);
            }
        }
        else if('*'==c||'/'==c||'('==c)
        {
            push(&s,c);
        }
        else if('#'==c)
        {
            break;
        }
        else
        {
            printf("
用户输入格式错误,瞎输入什么玩意
");
            return -1;
        }
        scanf("%c ",&c);
    }
    while(StackLen(s))
    {
        Pop(&s,&e),
        printf("%c ",e);
    }
    return 0;
}

点个赞再走哈~

原文地址:https://www.cnblogs.com/Kuller-Yan/p/12914123.html