顺序栈及中缀转后缀表达式的实现

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100

typedef char elemType;

typedef struct Stack{
    elemType data[MAXSIZE];
    int top;//栈顶指针
}Stack,*StackList;

void init(StackList l){
    l->top=0;//初始为0:每次数组最后一个位置空出来不使用,top总是指向栈顶的后一个位置;空间全部使用的话,初始就给到-1
}

//栈是否为空
int isEmpty(StackList l){
    return l->top==0;
}

//栈是否已经满了
int isFull(StackList l){
    return l->top == sizeof(l->data)/sizeof(l->data[0]);
}

//栈实际长度
int len(StackList l){
    return l->top;
}

//获取栈顶数据,C语言只能返回一个数据,返回数据用来展示执行结果,传个数据指针用来展示数据结果
int getTop(StackList l,elemType *e){
    if (isEmpty(l)){
        return 0;
    }
    *e=(l->data[l->top-1]);
    return 1;
}

//入栈
int push(StackList l,elemType e){
    if (isFull(l)){
        return 0;
    }
    l->data[l->top]=e;
    l->top+=1;
    return 1;
}

//出栈
elemType pop(StackList l,elemType *e){
    if (isEmpty(l)){
        return 0;
    }
    *e=l->data[l->top-1];
    l->top-=1;
    return 1;
}

//中缀表达式转后缀表达式 Reverse Polish Notation (RPN)
char result[MAXSIZE];//结果
char* midToBehind(char str[]){
    StackList l=(StackList)malloc(sizeof(Stack));
    init(l);
    int index=0;
    for (int i=0;i<MAXSIZE&&str[i]!='\0';i++){
        if (str[i]>='0'&&str[i]<='9'){//遇到数字直接加入后缀表达式
            result[index++]=str[i];
        }else if (str[i]=='('){//遇到'('入栈
            push(l,str[i]);
        }else if(str[i]==')'){//遇到')'出栈,直到遇到'(',期间出栈的运算符均加入后缀表达式
            char temp;
            int isSuc=pop(l,&temp);//不成功说明栈空了
            while(isSuc&&temp!='('){
                result[index++]=temp;
                isSuc=pop(l,&temp);
            }
        }else if(str[i]=='+'||str[i]=='-'){//+-优先级较低,四种运算符都可以弹出
            char temp;
            int isSuc=pop(l,&temp);
            while(isSuc&&(temp=='+'||temp=='-'||temp=='*'||temp=='/')){
                result[index++]=temp;
                isSuc=pop(l,&temp);
            }
            if (isSuc){
                push(l,temp);//多弹出了一个,先还回去
            }
            push(l,str[i]);
        }else if(str[i]=='*'||str[i]=='/'){
            char temp;
            int isSuc=pop(l,&temp);
            while(isSuc&&(temp=='*'||temp=='/')){
                result[index++]=temp;
                isSuc=pop(l,&temp);
            }
            if (isSuc){
                push(l,temp);//多弹出了一个,先还回去
            }
            push(l,str[i]);
        }
        printf("%s\n",result);
        printf("运算符栈中元素:%s\n",l->data);
    }
    //将栈中剩余的运算符弹出
    if (!isEmpty(l)){
        char temp;
        int isSuc=pop(l,&temp);
        while(isSuc){
            result[index++]=temp;
            isSuc=pop(l,&temp);
        }
    }
    return result;
}

int main(){
    char str[] = "3*4+(9/3+1)*6-1";
    midToBehind(str);
    printf("后缀表达式:%s\n",result);
}

猜你喜欢

转载自blog.csdn.net/qq_37575994/article/details/130982228