浙大版《数据结构(第2版)》题目集习题3.11 表达式转换 (25分)

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct snode{
    char ch[20];
    int top;
};
typedef struct snode *stack;
stack create(){
    stack s=(stack)malloc(sizeof(struct snode));
    s->top=-1;
    return s;
}
void push(stack s,char c){
    s->ch[++(s->top)] = c;
}
char pop(stack s){
    return s->ch[(s->top)--];
}

int main(){
    char priority[150];
    priority['(']=0;
    priority['+']=1;
    priority['-']=1;
    priority['*']=2;
    priority['/']=2;
    stack st=create();
    char fm[21];
    scanf("%s",fm);
    int len=strlen(fm);
    int flag=0;
    for(int i=0;i<len;i++){
        if(fm[i]=='('){
            push(st,fm[i]);
        }else if(fm[i]==')'){
            char t;
            t=pop(st);
            while(t!='('){
                printf(" %c",t);
                t=pop(st);
            }
            flag=1;
        }else if(fm[i]=='-'||fm[i]=='+'||fm[i]=='*'||fm[i]=='/'){
            if(fm[i]=='+' && (fm[i-1]=='(' || i==0)){
            }else if(fm[i]=='-' && (fm[i-1]=='(' || i==0)){
                printf("-");
            }else if(priority[fm[i]]>priority[st->ch[st->top]]||st->top==-1){
                push(st,fm[i]);
                flag=1;
            }else{
                printf(" %c",pop(st));
                while(priority[fm[i]]<=priority[st->ch[st->top]]&&st->top!=-1){
                    printf(" %c",pop(st));
                }
                push(st,fm[i]);
                flag=1;
            }
        }else{
            if(flag){
                printf(" ");
                flag=0;
            }
            printf("%c",fm[i]);
        }
    }
    while(st->top!=-1){
        printf(" %c",pop(st));
    }
    return 0;
}

思路中国大学mooc上有将,陈越的数据结构。
在这里插入图片描述

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页