-
Notifications
You must be signed in to change notification settings - Fork 118
/
224.c
134 lines (105 loc) · 2.7 KB
/
224.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct StackNode {
int val;
struct StackNode *next;
};
struct Stack {
struct StackNode *top;
struct StackNode *bottom;
};
void push(struct Stack *stack, int new_val) {
if (stack == NULL) return;
struct StackNode* new_node
= (struct StackNode *)malloc(sizeof(struct StackNode));
new_node->val = new_val;
new_node->next = stack->top;
stack->top = new_node;
if (stack->bottom == NULL) {
stack->bottom = new_node;
}
}
void pop(struct Stack *stack) {
if (stack == NULL || stack->top == NULL) return;
struct StackNode *t = stack->top;
stack->top = stack->top->next;
free(t);
if (stack->top == NULL) {
stack->bottom = NULL;
}
}
int top(struct Stack *stack) {
int ret = 0;
if (stack != NULL && stack->top != NULL) {
ret = stack->top->val;
}
return ret;
}
void destory(struct Stack *stack) {
if (stack == NULL || stack->top == NULL) return;
struct StackNode *t = NULL;
while (stack->top) {
t = stack->top;
stack->top = stack->top->next;
free(t);
}
stack->bottom = NULL;
}
int calculate(char* s) {
int ans = 0;
int n = 0;
char last_op = '+'; /* last operator */
bool flag = false; /* whether change the operator in parens or not */
struct Stack stack;
stack.top = stack.bottom = NULL;
push(&stack, flag);
while (*s != '\0') {
while (*s == ' ' || *s == '(') {
if (*s == '(') {
flag = (last_op == '-') ? true : false;
push(&stack, flag);
}
s++;
}
/* get an number */
n = 0;
while (*s >= '0' && *s <= '9') {
n = n * 10 + *s - '0';
s++;
}
/* do the math */
if (last_op == '+') {
ans += n;
}
else if (last_op == '-') {
ans -= n;
}
/* get next operator */
while (*s == ' ' || *s == ')') {
if (*s == ')') {
pop(&stack);
flag = top(&stack);
}
s++;
}
if (flag) {
last_op = (*s == '+') ? '-' : '+';
}
else {
last_op = *s;
}
s++;
}
destory(&stack);
return ans;
}
int main() {
char *s1 = "2-4-(8+2-6+(8+4-(1)+8-10))";
/* should be -15 */
printf("%s = %d\n", s1, calculate(s1));
char *s2 = "1-(2-(3-(4-5)))";
/* should be 3 */
printf("%s = %d\n", s2, calculate(s2));
return 0;
}