LeetCode 155 Min Stack(实现具有特殊操作的栈)

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

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

题目大意:实现一个支持push、pop、top以及getMin(返回栈中最小元素)操作的栈。

解题思路:利用动态数组模拟栈,每次push操作都将一个结构体入栈,结构体中包括当前入栈元素和当前栈中元素的最小值。每种作只需要常数时间。

代码如下:

typedef struct {
    int val;
    int min;
} Node;

typedef struct {
    Node *arr;
    int top;
    int size;
} MinStack;

/** initialize your data structure here. */
MinStack *minStackCreate(int maxSize) {
    MinStack *mstk = (MinStack *) malloc(sizeof *mstk);
    mstk->arr = (Node *) malloc(sizeof(Node) * (maxSize + 1));
    mstk->arr[0].min = INT_MAX;
    mstk->size = maxSize;
    mstk->top = 0;
    return mstk;
}

void minStackPush(MinStack *obj, int x) {
    obj->arr[++obj->top].val = x;
    if (obj->arr[obj->top-1].min > x) obj->arr[obj->top].min = x;
    else obj->arr[obj->top].min = obj->arr[obj->top-1].min;
}

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

int minStackTop(MinStack *obj) {
    return obj->arr[obj->top].val;
}

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

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

你可能感兴趣的:(数据结构)