Skip to content

Commit 186152e

Browse files
min stack
1 parent da84397 commit 186152e

File tree

1 file changed

+111
-0
lines changed

1 file changed

+111
-0
lines changed

week2/min-stack.c

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
typedef struct {
2+
int value;
3+
void *prev;
4+
} El;
5+
6+
typedef struct {
7+
El *top;
8+
int min;
9+
} MinStack;
10+
11+
/** initialize your data structure here. */
12+
MinStack* minStackCreate() {
13+
MinStack* new = malloc(sizeof(MinStack));
14+
15+
new->top = NULL;
16+
new->min = 0; // If stack has no elements
17+
18+
return new;
19+
}
20+
21+
void minStackPush(MinStack* obj, int x) {
22+
// Push
23+
El* new = malloc(sizeof(El));
24+
new->value = x;
25+
26+
// First element
27+
if (obj->top == NULL) {
28+
new->prev = NULL;
29+
obj->min = x;
30+
}
31+
// Other elements
32+
else {
33+
new->prev = obj->top;
34+
35+
// Handle min caching
36+
if (x < obj->min) {
37+
obj->min = x;
38+
}
39+
}
40+
41+
obj->top = new;
42+
}
43+
44+
void minStackPop(MinStack* obj) {
45+
if (obj->top != NULL) {
46+
El *toRemove = obj->top;
47+
obj->top = toRemove->prev;
48+
49+
// Recalculate minimum if needed
50+
if (toRemove->value == obj->min) {
51+
recalculateMin(obj);
52+
}
53+
54+
free(toRemove);
55+
}
56+
}
57+
58+
int minStackTop(MinStack* obj) {
59+
return obj->top->value;
60+
}
61+
62+
int minStackGetMin(MinStack* obj) {
63+
return obj->min;
64+
}
65+
66+
void minStackFree(MinStack* obj) {
67+
El *remove, *next = obj->top;
68+
69+
while (next != NULL) {
70+
remove = next;
71+
next = next->prev;
72+
73+
free(remove);
74+
}
75+
76+
free(obj);
77+
}
78+
79+
void recalculateMin(MinStack* obj) {
80+
El *next = obj->top;
81+
int min = 0;
82+
83+
if (next != NULL) {
84+
min = next->value;
85+
next = next->prev;
86+
87+
while (next != NULL) {
88+
if (next->value < min) {
89+
min = next->value;
90+
}
91+
next = next->prev;
92+
}
93+
}
94+
95+
obj->min = min;
96+
}
97+
98+
99+
/**
100+
* Your MinStack struct will be instantiated and called as such:
101+
* MinStack* obj = minStackCreate();
102+
* minStackPush(obj, x);
103+
104+
* minStackPop(obj);
105+
106+
* int param_3 = minStackTop(obj);
107+
108+
* int param_4 = minStackGetMin(obj);
109+
110+
* minStackFree(obj);
111+
*/

0 commit comments

Comments
 (0)