王培培 发表于 2013-8-16 10:22:09

[Microsoft面试]设计包含min 函数的栈

定义栈的数据结构,要求添加一个min 函数,能够得到栈的最小元素。要求函数min、push 以及pop 的时间复杂度都是O(1)。

王鹏 发表于 2013-8-16 10:28:47

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) error(“out of stack space.”);MinStackElement* p = stack.data;p->data = d;p->min = (stack.top==0?d : stack.data);if (p->min > d) p->min = d;top ++;}int MinStackPop(MinStack stack) {if (stack.top == 0) error(“stack is empty!”);return stack.data[--stack.top].data;}int MinStackMin(MinStack stack) {if (stack.top == 0) error(“stack is empty!”);return stack.data.min;}
页: [1]
查看完整版本: [Microsoft面试]设计包含min 函数的栈