zoukankan      html  css  js  c++  java
  • (微软100题)2.设计包含min 函数的栈。

    #include <iostream>
    using namespace std;
    /*2.设计包含min 函数的栈。
    定义栈的数据结构,要求添加一个min 函数,能够得到栈的最小元素。
    要求函数min、push 以及pop 的时间复杂度都是O(1)。
    ANSWER:
    Stack is a LIFO data structure. When some element is popped from the stack, the status will recover to the original status as before that element was pushed. So we can recover the minimum element, too. 
    */
    struct MinStackElement
    {
    	int data;
    	int min;
    };
    
    struct MinStack 
    {
    	MinStackElement * data;
    	int size;
    	int top;
    };
    
    MinStack MinStackInit(int maxSize) 
    {
    	MinStack stack;
    	stack.size = maxSize;
    	stack.data = (MinStackElement*) malloc(sizeof(MinStackElement)*maxSize);
    	stack.top = 0;
    	return stack;
    }
    void MinStackFree(MinStack stack) 
    {
    	free(stack.data);
    }
    void MinStackPush(MinStack stack, int d) 
    {
    	if (stack.top == stack.size) 
    		cout<<"out of stack space.";
    	MinStackElement* p = &stack.data[stack.top];
    	p->data = d;
    	p->min = (stack.top==0?d : stack.data[stack.top-1].min);
    	if (p->min > d) p->min = d;
    	stack.top ++;
    }
    int MinStackPop(MinStack stack) {
    	if (stack.top == 0) 
    		cout<<"stack is empty!";
    	return stack.data[--stack.top].data;
    }
    int MinStackMin(MinStack stack) {
    	if (stack.top == 0) 
    		cout<<"stack is empty!";
    	return stack.data[stack.top-1].min;
    }
    
    void main()
    {
    }
    

  • 相关阅读:
    Lucky Permutation Triple 构造
    HDU4283:You Are the One(区间DP)
    D. Match & Catch 后缀数组
    数学选讲 orz
    D
    一步一步线段树
    湖科大校赛第三题
    最大流部分
    bfs题目集锦
    hdu1429 bfs+状态压缩
  • 原文地址:https://www.cnblogs.com/byfei/p/6389846.html
Copyright © 2011-2022 走看看