栈的应用(计算逆波兰表达式)


说明:
1、本例程针对仅包含 + *和数字的逆波兰表达式
2、假设输入的逆波兰表达式合法
详细例程如下

#include 
#include 
typedef int ElementType;
#include "_Stack.h"
#include "_Stack.c"

#define SMALL_LEFT ( 40 )
#define SMALL_RIGHT ( 41 )

void Error( char* ErrorMsg )
{
	printf( "%s", ErrorMsg );
	exit( 1 );
} 

void FatalError( char* ErrorMsg )
{
	printf( "%s", ErrorMsg );
	exit( 2 );
}

int main()
{
	FILE *fp;
	Stack S;
	ElementType c;
	ElementType a, b, temp;

	if( ( fp = fopen( "postfix.txt", "r" ) ) == NULL )
	{
		printf( "Cannot open this file.\n" );
		return 0;
	}

	S = CreateStack();
	
	while( !feof ( fp ) )
	{
		c = fgetc( fp );
		if( c == ' ' )
			continue;
		if( c != '+' && c != '*' )
		{
			if( c < 48 || c > 57 )
			{
				break;
			}
			c -= 48;
			Push( c, S );
		}
		else
		{
			a = Top( S );
			Pop( S );
			b = Top( S );
			Pop( S );
			if( c == '+' )
			{
				Push( a + b, S );
			}
			else
				if( c == '*' )
				{
					Push( a * b, S );
				}
		}
	}
	printf( "%d", S->Next->Element );
	return 0;
}

输入样例: 6 5 2 3 + 8 * + 3 + *
输出值: 288


发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注