天天看点

逆波兰表达式生成(ps参照小甲鱼视频)

程序实现中缀表达式转换为后缀表达式,之间用空格分开。

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

#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10

typedef char Elemtype;
typedef struct
{
	Elemtype *base;
	Elemtype *top;
	int stacksize;
}Stack;

void InitStack(Stack *s);
void Push(Stack *s, Elemtype e);
void Pop(Stack *s, Elemtype *e);
int StackLen(Stack s);

int main()
{
	Stack s;
	char c,d;

	InitStack(&s);

	printf("输入:");	
	scanf("%c",&c);

	while (c != '#')
	{
		while(c >= '0' && c <= '9')
		{
			printf("%c", c);
			scanf("%c",&c);
			if (c < '0' || c > '9')
			{
				printf(" ");
			}
		}
		if (c == '(')
		{
			Push(&s, c);
		}
		else if (c == ')')
		{
			Pop(&s,&d);
			while (d != '(')
			{
				printf("%c ",d);
				Pop(&s,&d);
			}
		}
		else if (c == '+' || c == '-')
		{
			if (!StackLen(s))
			{
				Push(&s, c);
			}
			else
			{
				Pop(&s, &d);
				while (d != '('&& StackLen(s))
				{
					printf("%c ", d);
					Pop(&s, &d);
				}
				if (d == '(')
				{ 					
					Push(&s, d);
				}	
				if (!StackLen(s))
				{
					printf("%c ",d);
				}
				Push(&s, c);		
			}
		}
		else if (c == '*' || c == '/')
		{
			if (!StackLen(s))
			{
				Push(&s, c);
			}
			else
			{
				Pop(&s, &d);
				if (d == '+' || d == '-' || d=='(')
				{
					Push(&s, d);
				}
				else
				{					
					printf("%c ", d);
				}
				Push(&s, c);
			}
		}
		else if (c == '#')
		{
			break;
		}
		scanf("%c",&c);
	}
	while (StackLen(s))
	{
		Pop(&s, &d);
		printf("%c ", d);
	}

	return 0;
}

void InitStack(Stack *s)
{
	s->base = (Elemtype *)malloc(STACK_INIT_SIZE * sizeof(Elemtype));
	if (!s->base)
	{
		exit(0);
	}
	s->top = s->base;
	s->stacksize = STACK_INIT_SIZE;
}

void Push(Stack *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->stacksize += STACKINCREMENT;
	}
	*(s->top) = e;
	s->top++;
}

void Pop(Stack *s, Elemtype *e)
{
	if (s->top == s->base)
	{
		exit(0);
	}
	s->top--;
	*e = *(s->top);
}

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

运算示例:

逆波兰表达式生成(ps参照小甲鱼视频)