1. 程式人生 > >【資料結構】中綴表示式轉換字尾表示式(逆波蘭式)

【資料結構】中綴表示式轉換字尾表示式(逆波蘭式)

我的第一篇博文就是關於逆波蘭式的,現在回頭看感覺當時的程式碼太過混亂(不忍直視),在這裡對當時的程式碼進行一次重構。

#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
#define MaxSize 30
int Judge(int flag,char operater)
{
    if(flag)
        switch(operater){
            case '+': return 3;
            case '-': return 3;
            case
'*': return 5; case '/': return 5; case '(': return 1; case ')': return 6; } else switch(operater){ case '+': return 2; case '-': return 2; case '*': return 4; case '/': return 4; case '('
: return 6; case ')': return 1; } } void RPN(char *a) { int i = 0, j = 0; char b[MaxSize]; LinkStack *Stack; Stack = CreateStack(); while(a[i]){ if(a[i] >= '0' && a[i] <= '9'){ b[j++] = a[i]; i++; continue
; } while( !IsEmpty(Stack) && Judge(0,a[i]) < Judge(1,Stack->Next->Date)) b[j++] = Pop(Stack); if(IsEmpty(Stack)){ Push(Stack,a[i]); i++; continue; } else if(Judge(0,a[i]) > Judge(1,Stack->Next->Date)) Push(Stack,a[i]); else if(Judge(0,a[i]) == Judge(1,Stack->Next->Date)) Pop(Stack); i++; } while(!IsEmpty(Stack)) b[j++] = Pop(Stack); b[j] = '\0'; puts(b); } int main() { char a[MaxSize]; gets(a); RPN(a); return 0; }

下面是標頭檔案“stack.h”

#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
typedef struct Node{
    char Date;
    struct Node *Next;
} LinkStack;
LinkStack *CreateStack()
{
    LinkStack *S;
    S = (LinkStack*)malloc(sizeof(struct Node));
    S->Next = NULL;
    return S;
}
int IsEmpty(LinkStack *S)
{
    return(S->Next == NULL);
}
void Push(LinkStack *S, char item)
{
    LinkStack *TmpCell;
    TmpCell = (LinkStack*)malloc(sizeof(struct Node));
    TmpCell->Date = item;
    TmpCell->Next = S->Next;
    S->Next = TmpCell;
}
char Pop(LinkStack *S)
{
    LinkStack *FirstCell;
    char TopElem;
    if(IsEmpty(S)){
        printf("Stack is empty\n");
        return NULL;
    }
    else{
        FirstCell = S->Next;
        S->Next = FirstCell->Next;
        TopElem = FirstCell->Date;
        free(FirstCell);
        return TopElem;
    }
}

#endif // STACK_H_INCLUDED