计包含min 函数的栈。
定义栈的数据结构,要求添加一个min 函数,能够得到栈的最小元素。要求函数min、push 以及pop 的时间复杂度都是O(1)。解答: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[stack.top]; p->data = d; p->min = (stack.top==0?d : stack.data[top-1]); 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[stack.top-1].min;}
2021-11-13
最新推荐文章于 2022-01-29 16:30:08 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)