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

calculator.c

#include <stdio.h>
#include <stdlib.h>

#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;
}

更多视频、文章、嵌入式学习资料,微信关注 【学益得智能硬件】
在这里插入图片描述

发布了21 篇原创文章 · 获赞 47 · 访问量 9183

猜你喜欢

转载自blog.csdn.net/xiaopengX6/article/details/104710787
今日推荐