Skip to content

Commit 06db8d3

Browse files
Evaluate reverse polish notation
Signed-off-by: Leo Ma <begeekmyfriend@gmail.com>
1 parent bfc015f commit 06db8d3

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test eval_rpn.c
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
static int a2i(char *s)
5+
{
6+
int n = 0;
7+
int sign = 0;
8+
while (*s != '\0') {
9+
switch (s[0]) {
10+
case '+':
11+
break;
12+
case '-':
13+
sign = 1;
14+
break;
15+
case '*':
16+
break;
17+
case '/':
18+
break;
19+
default:
20+
n = n * 10 + (s[0] - '0');
21+
break;
22+
}
23+
s++;
24+
}
25+
return sign ? -n : n;
26+
}
27+
28+
static int evalRPN(char **tokens, int tokensSize)
29+
{
30+
int i, res, a, b;
31+
int stack[500], len = 0;
32+
33+
for (i = 0; i < tokensSize; i++) {
34+
switch (tokens[i][0]) {
35+
case '\0':
36+
break;
37+
case '+':
38+
if (len > 0) {
39+
b = stack[--len];
40+
}
41+
if (len > 0) {
42+
a = stack[--len];
43+
stack[len++] = a + b;
44+
}
45+
break;
46+
case '*':
47+
if (len > 0) {
48+
b = stack[--len];
49+
}
50+
if (len > 0) {
51+
a = stack[--len];
52+
stack[len++] = a * b;
53+
}
54+
break;
55+
case '/':
56+
if (len > 0) {
57+
b = stack[--len];
58+
}
59+
if (len > 0) {
60+
a = stack[--len];
61+
stack[len++] = a / b;
62+
}
63+
break;
64+
case '-':
65+
if (tokens[i][1] == '\0') {
66+
if (len > 0) {
67+
b = stack[--len];
68+
}
69+
if (len > 0) {
70+
a = stack[--len];
71+
stack[len++] = a - b;
72+
}
73+
break;
74+
}
75+
default:
76+
stack[len++] = a2i(tokens[i]);
77+
}
78+
}
79+
80+
return len > 0 ? stack[len - 1] : 0;
81+
}
82+
83+
int main(int argc, char **argv)
84+
{
85+
printf("%d\n", evalRPN(argv + 1, argc - 1));
86+
return 0;
87+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy