Design a stack containing min Functions
Question:
Define the data structure of the stack. Add a min function to obtain the minimum element of the stack.
The time complexity of the min, push, and pop functions is O (1 ).
Code:
# Include
# Include
# Define MAX_LEN_STACK 10 typedef struct {int stackList [MAX_LEN_STACK]; int top ;}stack;/* auxiliary stack space, minimum storage space */stack minStack ={ 0 }; /* initialize stack */int initStack (stack * s) {if (s = NULL) {return-1;} s-> top =-1; minStack. top =-1;}/* get the top element of the stack */int top (stack * s) {if (s = NULL | s-> top <0) {return-1;} return s-> stackList [s-> top];}/* add elements to the stack */int push (stack * s, int data) {int topData; if (s-> top = MAX_LEN_STACK-1) {Return-1;} s-> stackList [++ (s-> top)] = data;/* First modify the secondary stack. If the value is smaller than the current secondary stack value, the value is updated to the current stack. if it is larger than the current value, the previous minimum value */if (minStack. top <0) {minStack. stackList [++ minStack. top] = 0;/* The first default value is 0. The stack subscript is recorded here */} else {topData = top (& minStack ); if (s-> stackList [topData] <data) {minStack. stackList [++ minStack. top] = topData;} else {minStack. stackList [++ minStack. top] = s-> top;/* record index value */} return 0;}/* out stack */int pop (stack * s) {I F (s = NULL | s-> top <0) {return-1;} minStack. top --; return s-> stackList [s-> top --];}/* get the minimum value of the current stack */int min (stack * s) {if (s = NULL | s-> top <0) {return-1;} return s-> stackList [minStack. stackList [minStack. top];}/* determines whether the current stack is empty */bool empty (stack * s) {return (s-> top <0 )? True: false;} int main () {stack s; int a [] = {96, 4, 2, 34,232, 22, 1}; int I; initStack (& s); for (I = 0; I <7; I ++) {push (& s, a [I]); printf ("data % d, min % d \ n ", a [I], min (& s) ;}while (! Empty (& s) {printf ("pop % d \ n", pop (& s); printf ("min % d \ n ", min (& s);} return 0 ;}