C语言使用栈实现逆波兰表达式 | 四则运算 | 后缀表达式

calculator.c

#include 
#include 

#define OK        1000000
#define ERROR     1000001

struct node
{
	int data;
	struct node *next;
};
typedef struct node Node;

struct stack
{
	Node *top;
	int count;
};
typedef struct stack LinkStack;

int InitStack(LinkStack **S)
{
	(*S) = (LinkStack *)malloc(sizeof(LinkStack));
	if (*S == NULL)
	{
		return ERROR;
	}

	(*S)->top = NULL;
	(*S)->count = 0;

	return OK;
}

int EmptyStack(LinkStack *S)
{
	if (S == NULL)
	{
		return ERROR;
	}

	return ((S->count == 0) ? OK : ERROR);
}

int Push(LinkStack *S, int e)
{
	if (S == NULL)
	{
		return ERROR;
	}

	Node *p = (Node *)malloc(sizeof(Node));
	if (NULL == p)
	{
		return ERROR;
	}

	p->data = e;
	p->next = S->top;
	S->top = p;
	S->count++;

	return OK;
}

int GetTop(LinkStack *S)
{
	if(S->top == NULL)
	{
		return ERROR;
	}
	return (S->top->data);
}

int Priority(char ch)
{
	switch (ch)
	{
		case '(':
			return 3;
		case '*':
		case '/':
			return 2;
		case '+':
		case '-':
			return 1;
		default:
			return 0;
	}
}

int Pop(LinkStack *S)
{
	int e;

	if (S->top == NULL)
	{
		return ERROR;
	}

	Node *p = S->top;
	e = p->data;
	S->top = p->next;
	free(p);
	S->count--;

	return e;
}

int main()
{
	LinkStack *num, *opt;
	char a[100] = {0};
	int i = 0;
	int tmp = 0, j;

	if(InitStack(&num) != OK || InitStack(&opt) != OK)
	{
		return ERROR;
	}
	
	printf("Please Input Opt :\n");
	scanf("%s", a);

	while (a[i] != '\0' || EmptyStack(opt) != OK)
	{
		if (a[i] >= '0' && a[i] <= '9')
		{
			tmp = tmp * 10 + a[i] - '0';
			i++;
			if (a[i] < '0' || a[i] > '9')
			{
				Push(num, tmp);
				tmp = 0;
			}
		}
		else
		{
			if ((EmptyStack(opt) == OK) || (GetTop(opt) == '(' && a[i] != ')') || 
					(Priority(a[i]) > Priority(GetTop(opt))))
			{	
				Push(opt, a[i]);
				i++;
				continue;
			}

			if (GetTop(opt) == '(' && a[i] == ')')
			{
				Pop(opt);
				i++;
				continue;
			}

			if ((a[i] == ')' && GetTop(opt) != '(') || (a[i] == '\0' && EmptyStack(opt) != OK) || 
				Priority(a[i]) <= Priority(GetTop(opt)))
			{
				switch (Pop(opt))
				{
					case '+':
						Push(num, Pop(num) + Pop(num));
						break;
					case '-':
						j = Pop(num);
						Push(num, Pop(num) - j);
						break;
					case '*':
						Push(num, Pop(num) * Pop(num));
						break;
					case '/':
						j = Pop(num);
						Push(num, Pop(num) / j);
						break;
				}
				continue;
			}
		}
	}

	printf("result is %d\n", Pop(num));
	return 0;
}

更多视频、文章、嵌入式学习资料,微信关注 【学益得智能硬件】
C语言使用栈实现逆波兰表达式 | 四则运算 | 后缀表达式_第1张图片

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