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;
}