zoukankan      html  css  js  c++  java
  • 后缀式的转换

    /*  
    做这道题之前我用了一上午头的时间都没有明白怎么变成后缀式,但是一旦知道后缀式怎么变成表达式的时候思路就很清晰了(感谢秦川同学,尚灿芳同学//scanf= =...,赵鹏同学对小的不离不弃不厌倦= =。。。);


    转换成后缀式无非就是遵循保证优先级高或者是相等时候入栈的的先打出来(此题中即先出栈打印),遇到()时先把括号里的输出在输出括号外面的;

    */
    #include<stdio.h>
    #include<stdlib.h>
    struct stack
    {
    char c[100];
    int top;
    };

    int Push ( struct stack *p,char ch )
    {
    if( p->top == 49 )
    return 0;
    else
    {
    p->top++;
    p->c[p->top] = ch;
    return 1;
    }
    }

    int Pop ( struct stack *p,char *ch)
    {
    if( p->top<0 )return 0;
    else
    {
    *ch = p->c[p->top];
    p->top--;
    return 1;
    }

    }

    int sw(char c)//优先级的选择很重要。而且()的优先级也很重要,否则下面的思路会混乱
    {
    if(c=='+' || c=='-') return 1;
    if(c=='*' || c=='/') return 2;
    if(c=='(') return 3;
    if(c==')') return 4;
    }

    int main()
    {

    struct stack *p;
    char ch,a,*h,g;
    int i,leap = 0;
    h=&a;
    p = (struct stack *)malloc(sizeof(struct stack));
    p->top = -1;
    while((ch = getchar())!='#' )
    {
    if( ch <= 'z' && ch >= 'a') //若果是字母就打印出来
    {
    printf("%c",ch);
    }
    else //如果是标号****难点***
    {
    if(p->top == -1) //如果是栈底直接压入
    Push(p,ch);
    else
    {
    if(sw(ch)>=sw(p->c[p->top])) //如果输入的优先级高
    {
    if(ch == ')') //最高点是),如果是他就把(前的全部弹出
    {
    while(p->c[p->top]!='(')
    {
    printf("%c",p->c[p->top]);
    Pop(p,h);
    }
    Pop(p,h); //这一点很重要,是排出(
    }
    else //如果不是)就压入,不论是不是(;
    {
    Push(p,ch);
    }
    }
    else //如果输入的优先级低或者等于而且分两种情况
    {
    if(p->c[p->top]=='(') //低的话有两种可能一个是他是加减法,另一个就是前面的是‘(’(不可能是),因为它不入栈)
    {
    Push(p,ch); //直接压入
    }
    else
    {
    printf("%c",p->c[p->top]); //保证了存在站里面的(之前的永远是低的(换句话说就是+-)
    Pop(p,h);
    Push(p,ch);

    }
    }
    }
    }

    }
    while(p->top!=-1)
    {
    printf("%c",p->c[p->top]);
    Pop(p,h);
    }return 0;
    }
  • 相关阅读:
    经验谈 论前端架构的重要性
    论 Angular的混乱
    DTW 算法(转)
    软件提高发射功率原理
    (转)LSI SAS 1068E Raid CentOS 5.5 安装实例浪潮NF5220系列 分类: linux
    聚类算法总结
    信号相似性的描述
    python科学计算整理
    一个无线通信类投稿的期刊list
    2012年Elsevier旗下Computer Science期刊最新SCI影响因子排名
  • 原文地址:https://www.cnblogs.com/0803yijia/p/2364059.html
Copyright © 2011-2022 走看看