1. 程式人生 > >C語言利用棧實現將中綴表示式轉換為字尾表示式(即逆波蘭式)

C語言利用棧實現將中綴表示式轉換為字尾表示式(即逆波蘭式)

輸入計算表示式如:(1-3)*4+10/5

輸出的逆波蘭式:1  3  -  4  * 10  5  /   +

碼程式碼時臉上洋溢著的神祕的微笑微笑

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

#define Stack_Init_Size 20
#define Stack_Increasement 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)
    {
        return;
    }
    s->top=s->base;
    s->stacksize=Stack_Init_Size;
}

void push(sqStack *s,Elemtype e)
{
    if(s->top-s->base>=s->stacksize)
    {
        s->base=(Elemtype *)realloc(s->base,(Stack_Increasement+s->stacksize)*sizeof(Elemtype));
        if(!s->base)
        {
            return;
        }
    }
    *(s->top)=e;
    s->top++;
}

void pop(sqStack *s,Elemtype *e)
{
    if(s->top == s->base)
    {
        return;
    }
    s->top--;
    *e=*(s->top);
}

int stackLen(sqStack s)
{
    return (s.top-s.base);
}

int isEmpty(sqStack s)
{
    return (s.base==s.top);
}

int main()
{
    sqStack s;
    initStack(&s);
    char c,e;
    printf("請輸入所要計算的中綴表示式,以#結束!\n");
    scanf("%c",&c);
    while(c!='#')
    {
        while(isdigit(c))
        {
            printf("%c",c);
            scanf("%c",&c);  //如果此刻輸入#,則外層以#為結束條件的迴圈會無法結束,因為後面有讀入的語句,此時讀入的#會被“覆蓋”,所以外層迴圈內的要判斷讀入的c是否是#
            if(c>'9'||c<'0')
            {
                printf(" ");
            }
        }  //保證輸出的多位數的形式正確  如123不會輸出1 2 3
        if(')'==c)
        {
            pop(&s,&e);
            while( '(' != e )
            {
                printf("%c ",e);
                pop(&s,&e);
            }
        }
        else if('+'==c ||'-'==c)
        {
            if(isEmpty(s))
            {
                push(&s,c);
            }
            else
            {
                do
                {
                    pop(&s,&e);
                    if( '(' == e )
                    {
                       push(&s,e);
                    }
                    else
                    {
                        printf("%c ",e);
                    }
                }while(!isEmpty(s) && '('!=e);
                push(&s,c);
            }
        }
        else if( '*' == c || '/' == c || '(' == c )
        {
             push(&s,c);
        }
        else if('#'==c)
        {
            break;
        }
        else
        {
            printf("\n出錯:輸入格式錯誤!\n");
            return -1;
        }
        scanf("%c",&c);
    }
    while(!isEmpty(s))
    {
        pop(&s,&e);
        printf("%c ",e);
    }
	printf("\n");
    return 0;
}