1:逆波兰表达式:
逆波兰表达式(Reverse Polish Notation):有效的运算符包括 +, -, *, / 。
每个运算对象可以是整数,也可以是另一个逆波兰表达式。
输入: ["2", "1", "+", "3", "*"]
输出: 9
解释: ((2 + 1) * 3) = 9
分析:栈
遍历数组,逐渐压入栈中,如果遇到运算字符,则弹出栈顶两个元素,之后将计算结果再压入栈中
/*server.c*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
static bool isNum (char *elem)
{
if (strcmp(elem, "*") == 0 ||
strcmp(elem, "/") == 0 ||
strcmp(elem, "+") == 0) {
return false;
} else if (strcmp(elem, "-") == 0 && strlen(elem) == 1) {
return false;
}
return true;
}
#define OPERATIONNUM 4
int EvalRPN(char ** tokens, int tokensSize)
{
int i;
int result;
int *stack = (int *)malloc(sizeof(int) * tokensSize);
int count = 0;
for (i = 0; i < tokensSize; i++) {
if (isNum(tokens[i])) {
stack[count++] = atoi(tokens[i]); // push stack
} else if (isNum(tokens[i]) == false && i >= 2) {
char *opt = (char *)malloc(sizeof(char)*strlen(tokens[i]));
memcpy(opt, tokens[i], strlen(tokens[i])+1);
int first = stack[--count]; // pop stack
int second = stack[--count]; // pop stack;
if (!strcmp(opt, "*")) {
result = first * second;
} else if (!strcmp(opt, "-")) {
result = first - second;
} else if (!strcmp(opt, "/")) {
result = first / second;
} else if (!strcmp(opt, "+")) {
result = first + second;
}
stack[count++] = result; // push stack
free(opt);
}
}
return stack[0];
}
int main()
{
char* testArray[] = {"2", "1", "+", "3", "*"};
int result = EvalRPN(testArray, 5);
printf("The calc res is %d of testArray.\n", result);
}