C语言实现中缀表达式转成后缀表达式(如有不足请指正)

bool isLeftBracket(char* ch)
{
	return *(ch) == '(' ? 1 : 0;
}
;
bool isRightBracket(char* tmp_ch)
{
	return *(tmp_ch) == ')' ? 1 : 0;
};
bool isNumber(char* tmp_char)
{
	return isdigit(*(tmp_char));
};
int isoperator(char* tmp_char)
{
	int result;
	switch (*(tmp_char))
	{
	case '+':
	case '-':
	case '*':
	case '/':
		result = 1;
		break;
	default:
		result = 0;
		break;
	}
	return result;
};
int ComparPriority(char* charTop, char* tmp_ch)
{
	int lag_ch_1, lag_ch_2;
	int result;
	if (charTop == NULL)
	{
		result = 0;
		return result;
	}
	else
	{
		switch (*(charTop))
		{
		case '+':
		case'-':
			lag_ch_1 = 1;
			break;
		case'*':
		case'/':
			lag_ch_1 = 2;
		default:
			lag_ch_1 = 0;
			break;
		}
		switch (*(tmp_ch))
		{
		case '+':
		case'-':
			lag_ch_2 = 1;
			break;
		case'*':
		case'/':
			lag_ch_2 = 2;
		default:
			break;
		}
	}
	if (lag_ch_1 == lag_ch_2)
	{
		result = 1;
	}
	else
	{
		result = lag_ch_1 > lag_ch_2 ? 2 : 0;
	}
	/*2表示charTop的优先级高于tmp_ch的优先级*/
	return result;
};
int transform(char* ch)
{
	LinkStack* stack = NULL;
	LinkStack* store = NULL;
	store = SeqStack_Create();/*用来承接后缀表达式*/
	char* result = NULL;
	stack = SeqStack_Create();//创建栈
	char* tmp_ch = ch;
	while ((tmp_ch != NULL)&&(*(tmp_ch)!='\0'))
	{
		/*遇到是数字——>直接自加运算*/
		/*判断是否为左符号,如果是左符号选择压栈*/
		if (isLeftBracket(tmp_ch))
		{
			SeqStack_Push(stack, (void*)tmp_ch);
		}
		/*判断是右括号将栈顶元素输出,并直到匹配到左括号*/
		if (isRightBracket(tmp_ch))
		{
			result = (char*)SeqStack_Pop(stack);
			/*判断是否为左括号*/
			while (!isLeftBracket(result))
			{
				result = (char*)SeqStack_Pop(stack);
				/*存储到store栈中*/
				if (!isLeftBracket(result))
				{
					SeqStack_Push(store, (void*)result);
				}
			}
		}
		/*是数字直接压入栈*/
		if (isNumber(tmp_ch))
		{
			SeqStack_Push(store, (void*)tmp_ch);
		}
		/*判断是否为运算符*/
		char* charTop = NULL;
		if (isoperator(tmp_ch))
		{
			/*比较优先级(相同,高优先级以及低优先级)*/
			charTop = (char*)SeqStack_Top(stack);
			int num = 0;
			num = ComparPriority(charTop, tmp_ch);
			/*高优先级*/
			switch (num)
			{
			case 2:/*ch1(栈顶元素)的优先级高于ch2的优先级*/
				result = (char*)SeqStack_Pop(stack);
				printf("%s", *(result));
				break;
			case 1:/*栈顶元素和tmp_ch优先级相同*/
				result = (char*)SeqStack_Pop(stack);
				SeqStack_Push(stack, (void*)tmp_ch);
				break;
			case 0:/*栈顶元素的优先级低于tmp_ch的优先级*/
				SeqStack_Push(stack, (void*)tmp_ch);
				break;
			default:
				break;
			}
		}
		tmp_ch++;
	}
	while (SeqStack_Size(store)>0)
	{
		char* tmp = (char*)SeqStack_Pop(store);
		printf("%c", *(tmp));
	}
	return 0;
}
int main(void)
{
	int return_num;
	const char* ch = "8+11+(20*9)-4";
	return_num = transform(ch);
	return return_num;
}

你可能感兴趣的:(c语言,java,前端)