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

来源:互联网 发布:java连接ldap实例 编辑:程序博客网 时间:2024/06/05 11:07

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

Problem Description

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

Input

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

Output

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

Example Input

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

Example Output

ab*cde/-f*+
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#include<stdio.h>#include<stdlib.h>typedef char elemtype;typedef int status;#define MAXSIZE 100#define OVERFLOW -2#define another 50#define true 1#define false 0typedef struct{    elemtype *base;    elemtype *top;    int stacksize;}Sqstack;/*status isEmpty(Sqstack &S){    if(S.top == S.base)        return true;    else        return false;}*/elemtype getTop(Sqstack &S){    if(S.base == S.top)        return false;    else        return *(S.top-1);}void initStack(Sqstack &S){    S.base = new elemtype[MAXSIZE];    S.top = S.base;    S.stacksize = MAXSIZE;}void Push(Sqstack &S, elemtype e){    if(S.top-S.base >= S.stacksize){        S.base = (elemtype *)realloc(S.base,(another+S.stacksize)*sizeof(elemtype));        S.top = S.base + S.stacksize;        S.stacksize += another;    }    *S.top++ = e;}int Pop(Sqstack &S){S.top--;printf("%c",*S.top);return 0;}void LineEdit(Sqstack &S, char str[]){    int i = 0;    while(str[i] != '#'){        if(str[i] >= 'a'&&str[i] <= 'z'){            printf("%c",str[i]);        }        else if(str[i] == '*' || str[i] == '/'){            Push(S,str[i]);        }        else if(str[i] == '+' || str[i] == '-'){            if(*(S.top-1) == '*' || *(S.top-1)== '/'|| *(S.top-1)== '+' || *(S.top-1) == '-'){                Pop(S);            }            Push(S,str[i]);        }        else if(str[i]=='('){            Push(S,str[i]);        }        else if(str[i]==')'){            while(*(S.top-1)!='('){                Pop(S);            }            S.top--;        }        i++;    }    while(S.base!=S.top){        Pop(S);    }    printf("\n");}int main(){    Sqstack S;    initStack(S);    char string[123];    scanf("%s",string);    LineEdit(S, string);    return 0;}

阅读全文
0 0
原创粉丝点击