鱼C论坛

 找回密码
 立即注册
查看: 2594|回复: 0

求大家帮我看看这个代码:中缀表达式变后缀表达式 只输出1 谢谢大家了

[复制链接]
发表于 2017-9-29 15:17:01 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 百年c++ 于 2017-9-29 21:11 编辑

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>



#define STACK_INIT_SIZE 20
#define STACKINCREMENT  10
typedef char ElemType;
typedef struct
{
    ElemType *base;
    ElemType *top;
    int stacksize;
}SqStack;


InitStack(SqStack &S)
{
    S.base=(ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));
    if (!S.base) exit (0);
    S.top=S.base;
    S.stacksize=STACK_INIT_SIZE;
}

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+=STACKINCREMENT;
   }
   *S.top++=e;
   return 0;
}

Pop(SqStack &S,ElemType e)
{
    if (S.top==S.base) return 0;
    e=*--S.top;
}


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

int main()
{
    SqStack S;
     char c,e;
     InitStack(S);
    // printf ("请输入中缀表达式,以#作为结束标志:");
     scanf("%c",&c);
     getchar();
     while (c!='#')
     {
        while( c>='0'&&c<='9')
        {
            printf ("%c",c);
            scanf ("%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 ("\n出错:输入格式错误!");
            return -1;
        }*/
         scanf("%c",&c);
     }
     while (StackLen(S))
     {
         Pop(S,e);
         printf ("%c ",e);
     }
     return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-19 15:53

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表