Skip to content

Commit a99ae34

Browse files
author
lightmen
committed
add min-stack.c
1 parent 7fed83a commit a99ae34

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

min-stack.c

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
typedef struct {
2+
int *data;
3+
int *min;
4+
int top_data;
5+
int top_min;
6+
} MinStack;
7+
8+
void minStackCreate(MinStack *stack, int maxSize) {
9+
stack->data = (int *)malloc(sizeof(int) * maxSize);
10+
stack->min = (int *)malloc(sizeof(int) * maxSize);
11+
12+
stack->top_data = -1;
13+
stack->top_min = -1;
14+
}
15+
16+
void minStackPush(MinStack *stack, int element) {
17+
stack->data[++stack->top_data] = element;
18+
19+
if(stack->top_min == -1 || element <= stack->min[stack->top_min]){
20+
stack->min[++stack->top_min] = element;
21+
}
22+
}
23+
24+
void minStackPop(MinStack *stack) {
25+
int top = minStackTop(stack);
26+
if(top <= minStackGetMin(stack))
27+
stack->top_min--;
28+
29+
stack->top_data--;
30+
}
31+
32+
int minStackTop(MinStack *stack) {
33+
return stack->data[stack->top_data];
34+
}
35+
36+
int minStackGetMin(MinStack *stack) {
37+
return stack->min[stack->top_min];
38+
}
39+
40+
void minStackDestroy(MinStack *stack) {
41+
42+
}

0 commit comments

Comments
 (0)