forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0682-baseball-game.c
71 lines (62 loc) · 1.72 KB
/
0682-baseball-game.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
/*
Return the sum of all the scores on the record after applying all the operations.
Space: O(n)
Time: O(n)
Where n is the size of operations
*/
//-------Implementation of a stack--------
typedef struct stack {
int val;
struct stack* next;
} stack;
int sum(stack* s) {
if (s==NULL)
return 0;
return s->val + sum(s->next);
}
stack* add(stack* s, int value) {
stack* new_s = malloc(sizeof(stack));
new_s->val = value;
new_s->next = s;
return new_s;
}
stack* rmv(stack* s) {
if (s==NULL) {
printf("Impossible de supprimer un élément d'une pile vide");
return NULL;
}
stack* ans = s->next;
free(s);
return ans;
}
//------------Main algorithm-------------
int calPoints(char ** operations, int operationsSize){
stack* s = NULL;
for (int i=0; i<operationsSize; i++) {
if (operations[i][0]=='+') {
int to_add = s->val + (s->next)->val;
s = add(s, to_add);
} else if (operations[i][0]=='D') {
s = add(s, 2*(s->val));
} else if (operations[i][0]=='C') {
s = rmv(s);
} else { // It's a number
if (operations[i][0]=='-') { // It's a negative number
int n = 0;
for (int j=0; operations[i][j+1]!='\0'; j++) {
n *= 10;
n -= operations[i][j+1] - '0';
}
s = add(s, n);
} else { // It's a positive number
int n = 0;
for (int j=0; operations[i][j]!='\0'; j++) {
n *= 10;
n += operations[i][j] - '0';
}
s = add(s, n);
}
}
}
return sum(s);
}