C语言后缀表达式求值

后缀表达式求值的算法是 

遍历后缀表达式,如果遇到运算数,那么运算数入栈

如果遇到运算符,那么弹出栈里面两个元素,先弹出的是右运算数,后弹出的是左运算数,计算运算结果,然后将结果入栈。最后遍历到后缀表达式末尾,当结果只有一个元素时,就是答案

#define  _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 
#include "LinkStack.h"

int IsNumber(char c)
{
	return c >= '0' && c <= '9';
}


typedef struct MYNUM
{
	LinkNode node;
	int val;

}MyNum;

int Caculate(int left, int right, char c)
{
	int ret = 0;
	switch (c)
	{
	case '+':
		ret = left + right;
		break;
	case '-':
		ret = left - right;
		break;
	case '*':
		ret = left * right;
		break;
	case '/':
		ret = left / right;
		break;

	default:
		break;	
	}
	return ret;
}

int main()
{
	// 后缀表达式
	char str[50] = "831-5*+";
	char *p = str;
	LinkStack* stack = Init_LinkStack();
	while (*p != '\0')
	{
		if (IsNumber(*p))
		{
			MyNum* num = (MyNum*)malloc(sizeof(MyNum));
			num->val = *p - '0';
			Push_LinkStack(stack, (LinkNode*)num);
		}
		else
		{
			MyNum* temp = (MyNum*)Top_LinkStack(stack);
			int rightNum = temp->val;
			Pop_LinkStack(stack);
			free(temp);
			temp = (MyNum*)Top_LinkStack(stack);
			int leftNum = temp->val;
			Pop_LinkStack(stack);
			free(temp);
            
			int ret = Caculate(leftNum, rightNum, *p);

			MyNum* num = (MyNum*)malloc(sizeof(MyNum));
			num->val = ret;
			Push_LinkStack(stack, (LinkNode*)num);
			
		}
		p++;
	}
	if (Size_LinkStack(stack) == 1)
	{
		MyNum* num = (MyNum*)Top_LinkStack(stack);
		printf("运算结果是%d\n", num->val);
		Pop_LinkStack(stack);
		free(num);
	}
	//释放栈
	FreeSpace_LinkStack(stack);
	system("pause");
}

使用的栈是前面写的企业链式栈

你可能感兴趣的:(算法)