forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path150.c
82 lines (74 loc) · 1.79 KB
/
150.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node {
int val;
struct Node *next;
};
void push(struct Node** top_pt, int new_data)
{
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
new_node->val = new_data;
new_node->next = *top_pt;
*top_pt = new_node;
}
int pop(struct Node** top_pt)
{
if (*top_pt == NULL)
{
printf("stack overflow\n");
exit(0);
}
struct Node *top = *top_pt;
int res = top->val;
*top_pt = top->next;
free(top);
return res;
}
int evalRPN(char *tokens[], int n) {
struct Node *stack = NULL;
int i;
for (i = 0; i < n; i++)
{
if (strcmp(tokens[i], "+") == 0) {
int r = pop(&stack);
int l = pop(&stack);
push(&stack, l + r);
}
else if (strcmp(tokens[i], "-") == 0) {
int r = pop(&stack);
int l = pop(&stack);
push(&stack, l - r);
}
else if (strcmp(tokens[i], "*") == 0) {
int r = pop(&stack);
int l = pop(&stack);
push(&stack, l * r);
}
else if (strcmp(tokens[i], "/") == 0) {
int r = pop(&stack);
int l = pop(&stack);
push(&stack, l / r);
}
else
push(&stack, atoi(tokens[i]));
}
return pop(&stack);
}
void print_stack(struct Node** top_pt)
{
struct Node *t = *top_pt;
while (t != NULL)
{
struct Node *tmp_node = t;
printf("%d ", tmp_node->val);
t = tmp_node->next;
}
printf("\n");
}
int main()
{
char *tokens[] = {"3","-4","+"};
printf("%d\n", evalRPN(tokens, sizeof(tokens)/ sizeof(tokens[0])));
return 0;
}