Csdn.net
Question: improve the current stack data structure and add a min () function to make it possible to give the minimum value in the stack within a constant, that is, O (1. The push () and POP () functions can be modified, but the time complexity must be O (1 ).
Analysis: To make pop, push, and Min all O (1), we must sacrifice some space.
Idea: 1: Add a field to the data structure of the stack, as shown in figure
Typedef struct {
Int data [Max];
Int top;
Int min;
} Stack;
Pop, push all go to the top of the stack element, so it is O (1)
The min field of the stack is used when Min is used, so it is also O (1)
Compare each push. If the elements of the current push are smaller than those of stack-> min, replace stack-> min with the current element. As a result, Min is obtained. The procedure is as follows:
Int push (stack * s, int X ){
Assert (s! = NULL );
If (S-> top> = max)
{
Printf ("Stack overload! ");
Return-1;
}
S-> data [S-> top ++] = X;
If (x <s-> min)
S-> min = X;
Return 0;
}
Int POP (stack * s, int * X)
{
Assert (s! = NULL );
If (S-> top <= 0)
{
Printf ("Stack empty! ");
Return-1;
}
(* X) = S-> data [S-> top --];
Return 0;
}
Int min (stack * s, int * X)
{
Assert (s! = NULL );
(* X) = S-> min;
Return 0;
}
Note: In this case, if the number of pop is exactly min, the min cannot be set correctly. Therefore, this method does not work.
Idea 2: Set the secondary stack ass, record the minimum values in each State, and get the current value of the secondary stack at each insertion, and compare it with the inserted Value
If it is small, it is inserted into the minimum stack. Otherwise, it is the original minimum value. In this way, the three values are pop, push, and Min.
O (1) algorithm.
Typedef struct {
Int data [Max];
Int top;
} Stack;
Static int push_stack (stack * s, int X)
{
Assert (S! = NULL ));
If (S-> top> = max)
{
Printf ("Stack overload ");
Return-1;
}
S-> data [S-> top ++] = X;
Return 0;
}
Static int pop_stack (stack * s, int * X)
{
Assert (s! = NULL );
If (S-> top <= 0)
{
Printf ("Stack empty ");
Return-1;
}
(* X) = S-> data [S-> top --];
Return 0;
}
Int push (stack * Main, stack * ass, int X)
{
Assert (main! = NULL) & (ass! = NULL ));
Int temp;
Pop_stack (ass, & temp );
Push_stack (main, X );
If (x <temp)
{
Push_stack (ass, temp );
Push_stack (ass, X );
}
Else
{
Push_stack (ass, temp );
Push_stack (ass, temp );
}
Return 0;
}
Int POP (stack * Main, stack * ass, int * X)
{
Assert (main! = NULL) & (ass! = NULL ));
Int temp;
Pop_stack (ass, & temp );
Pop_stack (main, X );
Return 0;
}
Int min (stack * ass, int * X)
{
Assert (main! = NULL) & (ass! = NULL ));
Pop_stack (ass, X );
Push_stack (ass, (* X ));
Return 0;
}