逆波兰表达式数组用c语言和数组
时间: 2023-05-11 11:02:26 浏览: 98
可以使用栈来实现逆波兰表达式的计算。具体实现方法如下:
1. 定义一个栈,用于存储操作数和运算符。
2. 遍历逆波兰表达式数组,对于每个元素进行如下操作:
- 如果是操作数,将其压入栈中。
- 如果是运算符,从栈中弹出两个操作数,进行运算,并将结果压入栈中。
3. 遍历结束后,栈中只剩下一个元素,即为逆波兰表达式的计算结果。
以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STACK_SIZE 100
typedef struct {
int top;
int data[MAX_STACK_SIZE];
} Stack;
void push(Stack *s, int x) {
if (s->top == MAX_STACK_SIZE - 1) {
printf("Stack overflow\n");
exit(1);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (s->top == -1) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top--];
}
int evalRPN(char **tokens, int tokensSize) {
Stack s;
s.top = -1;
int i;
for (i = 0; i < tokensSize; i++) {
if (strcmp(tokens[i], "+") == 0) {
int b = pop(&s);
int a = pop(&s);
push(&s, a + b);
} else if (strcmp(tokens[i], "-") == 0) {
int b = pop(&s);
int a = pop(&s);
push(&s, a - b);
} else if (strcmp(tokens[i], "*") == 0) {
int b = pop(&s);
int a = pop(&s);
push(&s, a * b);
} else if (strcmp(tokens[i], "/") == 0) {
int b = pop(&s);
int a = pop(&s);
push(&s, a / b);
} else {
push(&s, atoi(tokens[i]));
}
}
return pop(&s);
}
int main() {
char *tokens[] = {"2", "1", "+", "3", "*"};
int tokensSize = sizeof(tokens) / sizeof(tokens[0]);
int result = evalRPN(tokens, tokensSize);
printf("%d\n", result);
return 0;
}
```
输出结果为:9。
注意:以上代码仅为示例,实际应用中需要进行错误处理等更完善的处理。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)