数据结构习题——8逆波兰式

time_limit

3000MS

memory_limit

10000KB

description

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

input

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

output

输出其逆波兰式。

sample_input

(a+b)*c

sample_output

ab+c*

#include <stdio.h>
//#include <iostream>
#include <stdlib.h>
#include <string.h>
#define N 100
//using namespace std;
typedef char Elemtype;
typedef struct node {
	Elemtype a[N];
	int pos;
}Stack, *PStack;

PStack Init_stack()
{
	PStack pstack;
	pstack = (PStack)malloc(sizeof(Stack));
	pstack->pos = -1;
	return pstack;
}

int isempty(PStack pstack)
{
	return (pstack->pos == -1);
}

Elemtype get_top(PStack pstack)
{
	return pstack->a[pstack->pos];
}

void push(PStack p, Elemtype x)
{
	if (p->pos == N - 1) { printf("Overflow"); return; }
	p->a[++p->pos] = x;
}

Elemtype pop(PStack p)
{
	Elemtype x;
	x = p->a[p->pos];
	p->pos--;
	return x;
}
int process(char a, char b)
{
	char aim[7][8] = { { ">><<<>>" },{ ">><<<>>" },{ ">>>><>>" },{ ">>>><>>" },{ "<<<<<=1" },{ ">>>>1>>" },{ "<<<<<1=" } };
	char sta[7] = { '+','-','*','/','(',')','#' };
	char result;
	int i, pa, pb;
	for (i = 0; i<6; i++) {
		if (a == sta[i])pa = i;
		if (b == sta[i])pb = i;
	}
	result = aim[pa][pb];
	if (result == '>')return 1;
	else if (result == '<')return -1;
	else return 0;
}

int isnum(char x)
{
	return ((x <= 'z') && x >= 'a');
}
int main()
{
	PStack p;
	char s[1000];
	//string s;
	int flag, i, len;
	char c, x;
	//cin >> s;
	gets(s);
	p = Init_stack();
	for (i = 0; s[i] != '\0';) {
		if (isnum(s[i])) {
			printf("%c", s[i++]);
		}
		else {
			if (isempty(p))
				push(p, s[i++]);
			else {
				flag = process(get_top(p), s[i]);
				if (flag == -1) {
					push(p, s[i++]);
				}
				else if (flag == 1) {
					printf("%c", pop(p));
					//i++;
				}
				else {
					pop(p);
					i++;
				}
			}
		}
	}
	for (; !isempty(p);) {
		if (p->a[p->pos] != '('&& p->a[p->pos] != ')')
			printf("%c", p->a[p->pos--]);
	}
	return 0;
}

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值