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

《数据结构与算法分析——c语言描述》读后笔记 4

2015-08-16 15:17 447 查看
栈:

中缀到后缀的转换。我们只允许操作+,*,(,)。
中缀表达式:a+b*c+(d*e+f)*g,后缀表达式:abc*+de*f+g*+
程序如下,stack.h如上篇博文中所示:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include"stack.h"

char* infix_to_postfix(char* str)
{
int i,j=0;
int SIZE=strlen(str);
if(str==NULL)
{
printf("empty string!!!\n");
return NULL;
}

Stack s=CreateStack(SIZE);

char *tmpstr=malloc(sizeof(char)*(SIZE+1));
if(tmpstr==NULL)
{
printf("tmpstr is empty!\n");
return NULL;
}

for(i=0;i<SIZE;++i)
{
if(str[i]=='+')
{
while(!IsEmpty(s) && Top(s)!='(' )
{
tmpstr[j++]=TopAndPop(s);
}
Push('+',s);
}

else if(str[i]=='*')
{
while(!IsEmpty(s) && Top(s)=='*')
{
tmpstr[j++]=TopAndPop(s);
}
Push('*',s);
}

else if(str[i]=='(')
{
Push(str[i],s);
}

else if(str[i]==')')
{
while(Top(s)!='(')
{
tmpstr[j++]=TopAndPop(s);
}
Pop(s);
}

else
{
tmpstr[j++]=str[i];
}
}
while(!IsEmpty(s))
{
tmpstr[j++]=TopAndPop(s);
}

return tmpstr;
}

int main()
{
char ss[]="a+b*c+(d*e+f)*g";
char* goal=infix_to_postfix(ss);
printf("the string is :%s\n",goal);

return 0;
}




在上面的程序中的if(str[i]=='+')语句后面加上如下两个语句并修改相应的*对应的else if语句,就可以在表达式中使用+,-,*,、,(,)了。
else if(str[i]=='-')
{
while(!IsEmpty(s) && Top(s)!='(' )
{
tmpstr[j++]=TopAndPop(s);
}
Push('-',s);
}
else if(str[i]=='/')
{
while(!IsEmpty(s) && (Top(s)=='*' || Top(s)=='/') )
{
tmpstr[j++]=TopAndPop(s);
}
Push('/',s);
else if(str[i]=='*')
{
while(!IsEmpty(s) && (Top(s)=='*' || Top(s)=='/') )
{
tmpstr[j++]=TopAndPop(s);
}
Push('*',s);
}


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