您的位置:首页 > 理论基础 > 数据结构算法

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

2016-10-03 23:24 295 查看

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

Time Limit: 1000MSMemory Limit: 65536KB
[align=center]SubmitStatistic[/align]

Problem Description

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

Input

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

Output

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

Example Input

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


Example Output

ab*cde/-f*+

 

#include<stdio.h>
#include<malloc.h>
#define maxsize 10000
#define plus 10
char a[10000];
struct node
{
 char *base;
 char *top;
 int stacksize;
};
int init(node &S)
{
 S.base=(char *)malloc(maxsize*sizeof(char));
 if(!S.base)return -1;
 S.top=S.base;
 S.stacksize=maxsize;
 return 0;
}
int push(node &S,char e)
{
 if(S.top-S.base>=S.stacksize)
 {
  S.base=(char *)malloc((S.stacksize+plus)*sizeof(char));
  if(!S.base)return -1;
  S.top=S.base+S.stacksize;
  S.stacksize=S.stacksize+plus;
 }
 *S.top=e;
 S.top++;
 return 0;
}
int pop(node &S)
{
 char e;
 S.top--;
 printf("%c",*S.top);
 return 0;
}
int creat(node &S,char a[])
{
 int i;
 int e;
 for(i=0;a[i]!='#';i++)
 {
  if(a[i]>='a'&&a[i]<='z'||a[i]>='A'&&a[i]<='Z')
  {
   printf("%c",a[i]);
  }
  else if(a[i]=='*'||a[i]=='/')push(S,a[i]);
  else if(a[i]=='(')push(S,a[i]);
  else if(a[i]==')')
  { 
   while(*(S.top-1)!='(')
   {
        pop(S);
   }
   S.top--;
  }
  else
  {
   if(*(S.top-1)=='*'||*(S.top-1)=='/')
   {
    pop(S);
   }
     push(S,a[i]);
  }
 }
 while(S.top!=S.base)pop(S);
 printf("\n");
 return 0;
}
int main()
{
 node S;
 scanf("%s",&a);
 init(S);
 creat(S,a);
 return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐