逆波兰式



Description

假设表达式由单字母变量和双目四则运算算符构成。试编写程序,将一个通常书写形式且书写正确的表达式转换为逆波兰式。

Input

输入由单字母变量和双目四则运算算符构成的表达式。

Output

输出其逆波兰式。

  • Sample Input 
    (a+b)*c
  • Sample Output
    ab+c*




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

typedef struct list
{
	char s;
	struct list* next;
}list;

typedef struct stack
{
	struct list* bottom;
	struct list* top;
}stack;

void init(list* l,stack* s)
{
	l->next = NULL;
	l->s = '.';
	s->top = l;
	s->bottom = l;
}

void push(stack* stack,char c)
{
	list* lnew = (list* )malloc(sizeof(list));
	lnew->s = c;
	lnew->next = stack->top;
	stack->top = lnew;
}

char pop(stack* stack)
{
	list* p;
	p = stack->top->next;
	char c;
	c = stack->top->s;
	free(stack->top);
	stack->top = p;
	return c;
}

int superior(char m,char n)//优先级表示,1表示优先级高,0表示低,2表示相等
{
	int k[6][6] = 
	{1,1,0,0,0,1,
	 1,1,0,0,0,1,
	 1,1,1,1,0,1,
	 1,1,1,1,0,1,
	 0,0,0,0,0,2,
	 1,1,1,1,-1,1};
	if(n == '.')
	{
		return 1;
	}
	else
	{
		int a = 0,b = 0;
		if(m == '+') a = 0;
		if(m == '-') a = 1;
		if(m == '*') a = 2;
		if(m == '/') a = 3;
		if(m == '(') a = 4;
		if(m == ')') a = 5;
		if(n == '+') b = 0;
		if(n == '-') b = 1;
		if(n == '*') b = 2;
		if(n == '/') b = 3;
		if(n == '(') b = 4;
		if(n == ')') b = 5;
		return k[a][b];
	}
}

int main()
{
	list* head = (list* )malloc(sizeof(list));
	stack* pstack = (stack* )malloc(sizeof(stack));
	init(head,pstack);
	char s;
	char m[1000];//利用字符数组存储输出数据
	int i, step = 0;
	
	while(1)
	{
		scanf("%c",&s);
		
		if(s == '\n')
		{
			break;
		}
		if(s >= 65 && s <= 90 || s >= 97 && s <= 122)//如果是字符,直接输出
		{
			m[step] = s;
			step++;
			continue;
		}
		if(s == '(')//如果是‘(’,入栈
		{
			push(pstack,s);
			continue;
		}
		if(s == ')')//如果是‘)’,将栈顶元素出栈,直到遇到‘(’(出栈但不输出)
		{
			while(pstack && pstack->top->s != '(')
			{
				//printf("%c", pstack->top->s);
				m[step] = pop(pstack);
				step++;
			}
			pop(pstack);
			continue;
		}
		if(superior(s,pstack->top->s) == 1)
		{
			push(pstack,s);
			continue;
		}
		else
		{
			while(superior(s,pstack->top->s) != 1 && pstack->top->s != '(')
			{
				m[step] = pop(pstack);
				step++;
			}
			push(pstack,s);
		}
	}
	
	for(i = 0;i < step;i++)
	{
		printf("%c",m[i]);
	}
	while(pstack->top != pstack->bottom)
	{
		printf("%c",pstack->top->s);
		pstack->top = pstack->top->next;
	}
	
	printf("\n");
	return 0;
}

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值