-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack.c
More file actions
75 lines (64 loc) · 1.43 KB
/
MinStack.c
File metadata and controls
75 lines (64 loc) · 1.43 KB
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
//https://leetcode.com/problems/min-stack/
#include<stdlib.h>
typedef struct node{
int n;
int minTillEnd;
struct node* next;
}node;
typedef struct {
node* head;
} MinStack;
MinStack* minStackCreate() {
MinStack* s=(MinStack* )malloc(sizeof(MinStack));
s->head=NULL;
return s;
}
void minStackPush(MinStack* obj, int val) {
if(!obj->head) {
obj->head=(node* )malloc(sizeof(node));
obj->head->n=val;
obj->head->minTillEnd=val;
obj->head->next=NULL;
return;
}
node* p=(node* )malloc(sizeof(node));
p->n=val;
if(val < obj->head->minTillEnd) p->minTillEnd=val;
else p->minTillEnd=obj->head->minTillEnd;
p->next=obj->head;
obj->head=p;
return;
}
void minStackPop(MinStack* obj) {
if(!obj->head) return;
node* p=obj->head;
obj->head=obj->head->next;
free(p);
p=NULL;
return;
}
int minStackTop(MinStack* obj) {
return obj->head->n;
}
int minStackGetMin(MinStack* obj) {
return obj->head->minTillEnd;
}
void minStackFree(MinStack* obj) {
node* p=obj->head,*q;
while(p){
q=p->next;
free(p);
p=q;
}
obj->head=NULL;
return;
}
/**
* Your MinStack struct will be instantiated and called as such:
* MinStack* obj = minStackCreate();
* minStackPush(obj, val);
* minStackPop(obj);
* int param_3 = minStackTop(obj);
* int param_4 = minStackGetMin(obj);
* minStackFree(obj);
*/