频道栏目
首页 > 资讯 > 其他 > 正文

编程习题—— Min Stack

17-09-26        来源:[db:作者]  
收藏   我要投稿

编程习题—— 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.

    代码如下:

    typedef struct {
        int* intStack;
        int top;
        int max;
    } MinStack;
    
    /** initialize your data structure here. */
    MinStack* minStackCreate(int maxSize) {
        MinStack* testStack;
        testStack=(MinStack*)malloc(sizeof(MinStack));
        testStack->top=-1;
        testStack->max=maxSize;
        testStack->intStack=(int*)malloc(sizeof(int)*maxSize);
        return testStack;
    }
    
    void minStackPush(MinStack* obj, int x) {
        obj->top+=1;
        *(obj->intStack+obj->top)=x;
    }
    
    void minStackPop(MinStack* obj) {
        obj->top-=1;
    }
    
    int minStackTop(MinStack* obj) {
        return *(obj->intStack+obj->top);
    }
    
    int minStackGetMin(MinStack* obj) {
        int min=INT_MAX;
        for(int n=0;n<=obj->top;n++)
        {
            if(*(obj->intStack+n)intStack+n);
            }
        }
        return min;
    }
    
    void minStackFree(MinStack* obj) {
        free(obj->intStack);
        free(obj);
    }
    
    /**
     * Your MinStack struct will be instantiated and called as such:
     * struct MinStack* obj = minStackCreate(maxSize);
     * minStackPush(obj, x);
     * minStackPop(obj);
     * int param_3 = minStackTop(obj);
     * int param_4 = minStackGetMin(obj);
     * minStackFree(obj);
     */
相关TAG标签
上一篇:学习report lab包的使用
下一篇:JavaScript的闭包详解介绍
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站