基於堆棧的方式:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *postfix_to_prefix(const char *string) {
char operator, *stack[1024];
int s = 0, number, fraction;
const char *tokens = string;
while (1) {
if (sscanf(tokens, "%1d.%2d", &number, &fraction) == 2) {
stack[s] = malloc(sizeof("1.00"));
(void) sprintf(stack[s++], "%4.2f", number + (fraction/100.0));
tokens += strlen("1.00");
} else if (sscanf(tokens, "%c", &operator) == 1) {
char *operand1 = stack[--s];
char *operand2 = stack[--s];
stack[s] = malloc(strlen(operand1) + strlen(operand1) + sizeof(operator) + sizeof('\0'));
(void) sprintf(stack[s++], "%c%s%s", operator, operand1, operand2);
free(operand1);
free(operand2);
tokens += sizeof(operator);
} else {
break;
}
}
return stack[--s];
}
int main() {
const char *string = "5.335.32*6.333.22++";
printf("%s\n", string);
char *inverted = postfix_to_prefix(string);
printf("%s\n", inverted);
free(inverted);
return 0;
}
輸出
> ./a.out
5.335.32*6.333.22++
++3.226.33*5.325.33
>
這是一個光禿禿的骨頭實現,沒有真正的錯誤檢查,也沒有其他收尾。您需要檢查減法和除法等非共享操作是否按照正確的順序與操作數一起出來,如果不是,則反轉它們。
首先,'5.335.32'需要分隔符如'5.33 5.32' – BLUEPIXY
@BLUEPIXY在這種情況下所有整數都是0.00格式,這會改變什麼嗎? – rezon
我明白了。但我認爲這需要額外的努力。 – BLUEPIXY