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[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;}
共 1 个关于本帖的回复 最后回复于 2013-8-16 10:28