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

来源:互联网 发布:手机淘宝返利网怎么用 编辑:程序博客网 时间:2024/06/11 12:00

Problem Description

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

Input

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

Output

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

Example Input

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

Example Output

ab*cde/-f*+

code:

#include<stdio.h>#include<stdlib.h>#include<string.h>#define STACK_INIT_SIZE 100#define STACKINCREMENT 10#define OVERLOAD -2#define ERROR 0#define OK 1typedef char ElemType;typedef struct{    ElemType *base;    ElemType *top;    int stacksize;}Sqstack;void InitStack(Sqstack &s)//初始化栈{    s.base = (ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));    if(!s.base)    {        exit(OVERLOAD);    }    s.top = s.base;    s.stacksize = STACK_INIT_SIZE;}int GetTop(Sqstack s, ElemType &e){    if(s.top == s.base) return ERROR;    e = *(s.top-1);    return OK;}void Push(Sqstack &s, ElemType e)//入栈{    if(s.top-s.base>=s.stacksize)    {        s.base = (ElemType*)realloc(s.base, (s.stacksize+STACKINCREMENT)*sizeof(ElemType));        if(!s.base) exit(OVERLOAD);        s.top = s.base+s.stacksize;        s.stacksize+=STACKINCREMENT;    }    *s.top++ = e;}int Pop(Sqstack &s, ElemType &e)//出栈,并将元素赋给e{    if(s.top == s.base) return ERROR;    e = *--s.top;    return OK;}int main(){    char s[10005];    Sqstack li;    InitStack(li);    scanf("%s", s);    int i = 0;    ElemType e;    while(s[i]!='#')    {        if(s[i]>='a'&&s[i]<='z')        {            printf("%c", s[i]);        }        else        {            if(s[i] == '*'||s[i] == '/')            {                Push(li, s[i]);            }            else if(s[i] == '+'||s[i] == '-')            {                while(li.top!=li.base&&*(li.top-1)!='(')//此时为+-时需要一直输出到此为止,不是只输出栈顶就结束                {                    Pop(li, e);                    printf("%c", e);                }                Push(li, s[i]);            }            else if(s[i]=='(') Push(li, s[i]);            else if(s[i] == ')')            {                while(*(li.top-1)!='(')                {                    Pop(li, e);                    printf("%c", e);                }                Pop(li, e);            }        }        i++;    }    while(GetTop(li, e)!=ERROR)//输出栈中剩余的元素    {        Pop(li, e);        printf("%c", e);    }    printf("\n");}


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