首页 > 编程语言 > 详细

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

时间:2015-08-16 16:46:59      阅读:388      评论:0      收藏:0      [点我收藏+]

栈:


中缀到后缀的转换。我们只允许操作+,*,(,)。

中缀表达式: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);
	}

技术分享

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

原文:http://yuzwei.blog.51cto.com/10126623/1685003

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!