标签:
定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。要求函数min、push以及pop的时间复杂度都是O(1)。
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct MinStackElement { int data; int min; }MinStackElement_T; typedef struct MinStack { MinStackElement_T* data; int size; int top; }MinStack_T; MinStack_T stack; void MinStackInit(int maxSize) { stack.size = maxSize; stack.top= 0; stack.data= (MinStackElement_T*) malloc(sizeof(MinStackElement_T)*maxSize); memset(stack.data, 0, sizeof(MinStackElement_T)*maxSize); return; } void MinStackFree() { free(stack.data); } void MinStackPush(int d) { if(stack.top == stack.size) { printf("out of stack space."); return; } MinStackElement_T* 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() { if(stack.top <= 0) { printf("stack is empty!\n"); return -1; } return stack.data[--stack.top].min; } int MinStackMin() { if(stack.top == 0) { printf("no min element!\n"); return -1; } return stack.data[stack.top-1].min; } int main(void) { MinStackInit(8); MinStackPush(10); printf("%d\n",MinStackMin()); MinStackPush(7); printf("%d\n",MinStackMin()); MinStackPush(3); printf("%d\n",MinStackMin()); MinStackPush(3); printf("%d\n",MinStackMin()); MinStackPush(8); printf("%d\n",MinStackMin()); MinStackPush(5); printf("%d\n",MinStackMin()); MinStackPush(2); printf("%d\n",MinStackMin()); MinStackPush(6); printf("%d\n",MinStackMin()); printf("------------------------\n"); printf("%d\n",MinStackMin()); MinStackPop(); printf("%d\n",MinStackMin()); MinStackPop(); printf("%d\n",MinStackMin()); MinStackPop(); printf("%d\n",MinStackMin()); MinStackPop(); printf("%d\n",MinStackMin()); MinStackPop(); printf("%d\n",MinStackMin()); MinStackPop(); printf("%d\n",MinStackMin()); MinStackPop(); printf("%d\n",MinStackMin()); MinStackPop(); printf("%d\n",MinStackMin()); MinStackPop(); printf("%d\n",MinStackMin()); MinStackPop(); printf("%d\n",MinStackMin()); MinStackFree(); /*打印 10 7 3 3 3 3 2 2 ------------------------ 2 2 3 3 3 3 7 10 no min element! -1 stack is empty! no min element! -1 stack is empty! no min element! -1 */ return 0; }
标签:
原文地址:http://blog.csdn.net/qisefengzheng/article/details/51329789