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

来源:互联网 发布:java构造set get方法 编辑:程序博客网 时间:2024/06/05 08:42

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

Time Limit: 1000MSMemory Limit: 65536KB
SubmitStatistic

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 10char 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;}
0 0