栈:


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

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

wKiom1XQOPjyKlL_AAD0NhTKcTY823.jpg


在上面的程序中的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);
	}

wKiom1XQQBXBQPRwAADsBI3lPts135.jpg