数据结构实验之栈二:一般算术表达式转换成后缀式

来源:互联网 发布:知乎日报和读读日报 编辑:程序博客网 时间:2024/06/17 05:56

数据结构实验之栈二:一般算术表达式转换成后缀式

Time Limit: 1000MS Memory limit: 65536K

题目描述

对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。

输入

输入一个算术表达式,以‘#’字符作为结束标志。

输出

输出该表达式转换所得到的后缀式。

示例输入

a*b+(c-d/e)*f#

示例输出

ab*cde/-f*+

提示

 

#include<stdio.h>

#include<stdlib.h>
#define maxsize 10000
#define sizenum 10000
typedef struct
{
 char *base;
 char *top;
 int stsize;
}Sq;
int stack_Init(Sq*s)//初始化
{
 s->base=(char *)malloc(maxsize*sizeof(char));
 if(!s->base)
exit(0);
 s->top=s->base;
 s->stsize=maxsize;
 return 1;
}
void push(Sq*s,char e)
{
 if(s->top-s->base>s->stsize)
 {
   s->base=(char *)realloc(s->base,(s->stsize+sizenum)*sizeof(char));
   if(!s->base)
  exit(0);
   s->top=s->base+s->stsize;
   s->stsize+=sizenum;
 }
 *s->top++=e;


}
void pop(Sq*s)
{
 
s->top--;
   printf("%c",*s->top);


}
void choose(Sq*s,char a[])
{
 for(int i=0;a[i]!='#';i++)
 {
   if(a[i]>='a'&&a[i]<='z')
   {
     printf("%c",a[i]);
   }
   else if(a[i]=='*'||a[i]=='/')
   {
     push(s,a[i]);
   }
   else if(a[i]=='+'||a[i]=='-')
   {
   if(*(s->top-1)=='*'||*(s->top-1)=='/')
   {
     pop(s);
   }
   push(s,a[i]);
   }
 else if(a[i]=='(')
 {
push(s,a[i]);
 }
 else if(a[i]==')')
 {
   while(*(s->top-1)!='(')
   {
    pop(s);
   }
   s->top--;
 }
 }
 while(s->top!=s->base)
 {
  pop(s);
 }
 printf("\n");
}
int main()
{
 Sq s;
 char a[maxsize];
 gets(a);
 stack_Init(&s);
 choose(&s,a);
 return 0;


}

0 0