數據結構習題——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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章