-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode155-min-stack.cpp
62 lines (52 loc) · 1005 Bytes
/
leetcode155-min-stack.cpp
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
// https://leetcode.com/problems/min-stack/
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int value;
Node* next;
Node(int value) {
this->value = value;
this->next = NULL;
}
};
bool isEmpty(Node* head) {
return head == NULL;
}
class MinStack {
public:
Node* head;
MinStack() {
this->head = NULL;
}
void push(int value) {
Node* node = new Node(value);
if (isEmpty(this->head)) {
this->head = node;
} else {
Node* tmp = head;
head = node;
head->next = tmp;
}
}
void pop() {
if (!isEmpty(this->head))
this->head = this->head->next;
return;
}
int top() {
if(!isEmpty(this->head))
return head->value;
return -1;
}
int getMin() {
int minVal = numeric_limits<int>::max();
Node* currPos = this->head;
while(currPos != NULL) {
minVal = min(minVal, currPos->value);
currPos = currPos->next;
}
return minVal;
}
};