C语言中缀表达式转后缀表达式

时间:2022-07-25
本文章向大家介绍C语言中缀表达式转后缀表达式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

众所周知,计算机中不能直接用中缀表达式计算,形如(1+2)*(4-5)之类的,但是我们可以计算机可以很容易的通过后缀表达式来计算我们所输入的算式。所以我们就需要把中缀表达式转换为后缀表达式。下面是个人写的一点代码,大家可以参考。

开始

添加适当的头文件,定义一个栈数据结构,

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#define  STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef char ElemType;

typedef struct
{
	ElemType *base;
	ElemType *top;
	int stackSize;
}SqStack;

创建一个栈

//创建一个栈
void initStack(SqStack *s) {
	s->base = (ElemType *)malloc(sizeof(ElemType));
	if (!s->base)
	{
		exit(0);
	}
	s->top = s->base;   //最开始 栈底就是栈顶
	s->stackSize = STACK_INIT_SIZE;
}

入栈操作

void Push(SqStack *s, ElemType e) {
	//如果栈满  追加空间
	if (s->top - s->base >= s->stackSize)
	{
		s->base = (ElemType *)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(ElemType));
		if (!s->base)
		{
			exit(0);
		}
		s->top = s->base + s->stackSize;  //设置栈顶
		s->stackSize = s->stackSize + STACKINCREMENT;
	}
	*(s->top) = e;
	s->top++;
}

出栈操作

void Pop(SqStack *s, ElemType *e) {
	if (s->top == s->base)
	{
		return;
	}
	*e = *--(s->top);
}

计算栈的当前容量(最大容量是s.stackSize)

int StackLen(SqStack s) {
	return (s.top - s.base);
}

主函数

int main() {
	char cal[50];
	char c, e;
	SqStack s;
	initStack(&s);
	printf("请输入中缀表达式 输入#表示结束n");
	scanf_s("%c", &c);
	while (c != '#')
	{
		while (c>='0' && c<='9')
		{
			printf("%c ", c);
			scanf_s("%c", &c);
			if (c<'0' || c>'9')
			{
				printf(" ");
			}
		}
		if (c == ')')
		{
			Pop(&s, &e);
			while (e != '(')
			{
				printf("%c ", e);
				Pop(&s, &e);
			}
		}
		else if (c == '+' || c == '-')
		{
			if (!StackLen(s))
			{
				Push(&s, c);
			}
			else {
				do
				{
					Pop(&s, &e);
					if (e == '(')
					{
						Push(&s, e);
					}
					else {
						printf("%c ", e);
					}
				} while (StackLen(s) && e!='(');
				Push(&s, c);
			}
		}else if (c=='*' || c=='/' || c=='(')
		{
			Push(&s, c);
		}else if (c=='#')
		{
			break;
		}
		else {
			printf("出错,输入格式错误");
			return -1;
		}
		scanf_s("%c", &c);
	}
	while (StackLen(s))
	{
		Pop(&s, &e);
		printf("%c ", e);
	}
	return 0;cd
}

本人用的是vs2015编译器,所以文中的scanf用了更安全的scanf_s, 如有引用 请自觉替换成和自己的编译器想匹配的函数 代码很简单 ,仔细看看研究一下指针就很容易看懂,

注:

  • 上述代码在visual studio 2015中编译成功运行,其他ide请自行测试
  • 上述文字皆为个人看法,如有错误或建议请及时联系我