http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2132
数据结构实验之栈二:一般算术表达式转换成后缀式
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
输入
输入一个算术表达式,以‘#’字符作为结束标志。
输出
输出该表达式转换所得到的后缀式。
示例输入
a*b+(c-d/e)*f#
示例输出
ab*cde/-f*+
#include<stdio.h>
#include<stdlib.h>
#define maxsize 10000
typedef char selement;
typedef struct
{
selement *top;
selement *base;
int stacksize;
}st;
int creat(st &S)
{
S.base=(selement *)malloc(maxsize*sizeof(selement));
if(!S.base) exit(0);
S.top=S.base;
S.stacksize=maxsize;
return 1;
}
int push(st &S,selement e)
{
if(S.top-S.base>=S.stacksize)
{
S.base=(selement *)realloc(S.base,
(S.stacksize+maxsize)*sizeof(selement));
if(!S.base) exit(0);
S.top=S.base+S.stacksize;
S.stacksize+=maxsize;
}
*(S.top++)=e;
return 1;
}
int pop(st &S,selement &e)
{
if(S.top==S.base)
return 0;
e=*(--S.top);
return 1;
}
int reads(st S,selement &e)
{
selement *r;
r=S.top;
if(r==S.base)
return 0;
e=*(--S.top);
return 1;
}
void func(st &S,char ch)
{
char e;
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')')
{
if(ch=='+'||ch=='-')
{
reads(S,e);
if(e=='*'||e=='/')
{
pop(S,e);
printf("%c",e);
push(S,ch);
}
else
push(S,ch);
}
else if(ch=='*'||ch=='/'||ch=='(')
{
push(S,ch);
}
else
{
do
{
pop(S,e);
if(e!='(')
printf("%c",e);
}while(e!='(');
}
}
else
printf("%c",ch);
}
int main()
{
char ch;
st S;
creat(S);
while(~scanf("%c",&ch)&&(ch!='#'))
{
func(S,ch);
}
while(S.top>S.base)
{
pop(S,ch);
printf("%c",ch);
}
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#define maxsize 10000
typedef char selement;
typedef struct
{
selement *top;
selement *base;
int stacksize;
}st;
int creat(st &S)
{
S.base=(selement *)malloc(maxsize*sizeof(selement));
if(!S.base) exit(0);
S.top=S.base;
S.stacksize=maxsize;
return 1;
}
int push(st &S,selement e)
{
if(S.top-S.base>=S.stacksize)
{
S.base=(selement *)realloc(S.base,
(S.stacksize+maxsize)*sizeof(selement));
if(!S.base) exit(0);
S.top=S.base+S.stacksize;
S.stacksize+=maxsize;
}
*(S.top++)=e;
return 1;
}
int pop(st &S,selement &e)
{
if(S.top==S.base)
return 0;
e=*(--S.top);
return 1;
}
int reads(st S,selement &e)
{
selement *r;
r=S.top;
if(r==S.base)
return 0;
e=*(--S.top);
return 1;
}
void func(st &S,char ch)
{
char e;
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')')
{
if(ch=='+'||ch=='-')
{
reads(S,e);
if(e=='*'||e=='/')
{
pop(S,e);
printf("%c",e);
push(S,ch);
}
else
push(S,ch);
}
else if(ch=='*'||ch=='/'||ch=='(')
{
push(S,ch);
}
else
{
do
{
pop(S,e);
if(e!='(')
printf("%c",e);
}while(e!='(');
}
}
else
printf("%c",ch);
}
int main()
{
char ch;
st S;
creat(S);
while(~scanf("%c",&ch)&&(ch!='#'))
{
func(S,ch);
}
while(S.top>S.base)
{
pop(S,ch);
printf("%c",ch);
}
return 0;
}