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

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

2016-08-03 21:13 393 查看


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




Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^



题目描述

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


输入

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


输出

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


示例输入

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



示例输出

ab*cde/-f*+


输入完成后,遍历数组,当a[i]是字母时 直接输出,当a[i]是 + - 时,除了栈顶是空或者是 "(" 时,都要把栈内的字符弹出,然后 a[i] 入栈。当 a[i] 是 * / 时,只要不遇到 栈顶是 *
/ , a[i] 都要入站。栈顶是 * / 时,弹出即可。当 a[i]是 “(” 时,入栈即可。当a[i]是")",弹出()之间的所有栈内字符。a数组内的最后一个字符是结束字符#,可以不遍历到它。

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

typedef struct {

char *base;

char *top;

int Lsize;

}Sqstack;

Sqstack push(Sqstack &s,char e){

*s.top++=e;

}

char gettop(Sqstack &s)

{

char e;

e=*(s.top-1);

return e;

}

char pop(Sqstack &s){char a;

if(s.top==s.base)return -1;

s.top--;

a=*s.top;

if(a!='('&&a!=')')

printf("%c",a);

return a ;

}

int Empty(Sqstack &s){

if(s.top==s.base) return 1;

else return 0;

}

char clearstack(Sqstack &s){

s.top=s.base;

}

int main()

{

int i,j,len;

char a[1001],b;

Sqstack S;

S.base=(char *)malloc(1010*sizeof(char));

S.top=S.base;

//push(S,'#');

scanf("%s",&a);

len=strlen(a);

for(i=0;i<len-1;i++){

if(a[i]>=97&&a[i]<=122)

printf("%c",a[i]);

else if(a[i]=='+'||a[i]=='-'){

while(!Empty(S)&&gettop(S)!='('){

pop(S);

}

push(S,a[i]);

}

else if(a[i]=='/'||a[i]=='*'){

while(gettop(S)=='*'||gettop(S)=='/'&&!Empty(S))

{

pop(S);

}

push(S,a[i]);

}

else if(a[i]=='('){

push(S,a[i]);

}

else if(a[i]==')'){

while(gettop(S)!='('){

pop(S);

}

pop(S);

}

while(i==len-2&&!Empty(S)){

pop(S);

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: