C語言中綴表達式轉后綴表達式

眾所周知,計算機中不能直接用中綴表達式計算,形如(1+2)*(4-5)之類的,但是我們可以計算機可以很容易的通過后綴表達式來計算我們所輸入的算式。所以我們就需要把中綴表達式轉換為后綴表達式。下面是個人寫的一點代碼,大家可以參考。

開始

添加適當的頭文件,定義一個棧數據結構,

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#define  STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef char ElemType;

typedef struct
{
    ElemType *base;
    ElemType *top;
    int stackSize;
}SqStack;

創建一個棧

//創建一個棧
void initStack(SqStack *s) {
    s->base = (ElemType *)malloc(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)
    {
        s->base = (ElemType *)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(ElemType));
        if (!s->base)
        {
            exit(0);
        }
        s->top = s->base + s->stackSize;  //設置棧頂
        s->stackSize = s->stackSize + STACKINCREMENT;
    }
    *(s->top) = e;
    s->top++;
}

出棧操作

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

計算棧的當前容量(最大容量是s.stackSize)

int StackLen(SqStack s) {
    return (s.top - s.base);
}

主函數

int main() {
    char cal[50];
    char c, e;
    SqStack s;
    initStack(&s);
    printf("請輸入中綴表達式 輸入#表示結束\n");
    scanf_s("%c", &c);
    while (c != '#')
    {
        while (c>='0' && c<='9')
        {
            printf("%c ", c);
            scanf_s("%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_s("%c", &c);
    }
    while (StackLen(s))
    {
        Pop(&s, &e);
        printf("%c ", e);
    }
    return 0;cd
}

以下是運行結果 本人用的是vs2015編譯器,所以文中的scanf用了更安全的scanf_s, 如有引用 請自覺替換成和自己的編譯器想匹配的函數

cmd 運行結果

代碼很簡單 ,仔細看看研究一下指針就很容易看懂,

注:

  • 上述代碼在visual studio 2015中編譯成功運行,其他ide請自行測試
  • 上述文字皆為個人看法,如有錯誤或建議請及時聯系我
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容