---
# System prepended metadata

title: LeetCode 155. Min Stack
tags: [Leetcode]

---

---
title: 'LeetCode 155. Min Stack'
disqus: hackmd
---

# LeetCode 155. Min Stack



## Description

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Implement the MinStack class:

* MinStack() initializes the stack object.
* void push(int val) pushes the element val onto the stack.
* void pop() removes the element on the top of the stack.
* int top() gets the top element of the stack.
* int getMin() retrieves the minimum element in the stack.

## Example

Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top();    // return 0
minStack.getMin(); // return -2

## Constraints

-2^31^ <= val <= 2^31^ - 1
Methods pop, top and getMin operations will always be called on non-empty stacks.
At most 3 * 10^4^ calls will be made to push, pop, top, and getMin.

## Answer

此題實作stack，先開一個固定空間，push就塞進去，top++。而pop就 top--即可。

```Cin=
//2021_11_22
typedef struct {
    int *nums;
    int *min;
    int size;
    int top;
} MinStack;


MinStack* minStackCreate() {
    MinStack *obj = (MinStack*)malloc(sizeof(MinStack));
    obj->size = 1000;
    obj->nums = (int*)malloc(sizeof(int)*obj->size);
    obj->min = (int*)malloc(sizeof(int)*obj->size);
    obj->top = 0;
    return obj;
}

void minStackPush(MinStack* obj, int val) {
  if(obj->top < obj->size){
      obj->nums[obj->top] = val;
      if(obj->top == 0){obj->min[obj->top] = val;}
      else{obj->min[obj->top] = obj->min[obj->top - 1] < val ? obj->min[obj->top - 1] : val;}
      (obj->top)++;
  }
}

void minStackPop(MinStack* obj) {
  if(obj->top > 0){
      (obj->top)--;
  }
}

int minStackTop(MinStack* obj) {
  return obj->nums[obj->top - 1];
}

int minStackGetMin(MinStack* obj) {
  return obj->min[obj->top - 1];
}

void minStackFree(MinStack* obj) {
    free(obj->nums);
    free(obj->min);
    free(obj);
}

```



## Link
https://leetcode.com/problems/min-stack/
###### tags: `Leetcode` 
