Question 2
Question: A stack is required. The stack contains the min function, that is, min, pop, and push operations can be performed in O (1) time.
Analysis:
Because the traditional stack only supports the push and pop functions, the push and pop functions are all performed in O (1) time, and the question requires the min function, that is, after the pop and push operations
Returns the minimum value in O (1. If the min function is directly added, it is O (N) time every time the minimum value is calculated. In order to reach O (1) time,
Array to store this dynamic change process. min_array [k] In min_array stores the minimum values of the first K numbers.
Code:
[Cpp]
# Include <iostream>
Using namespace std;
Template <class T>
Class Stack {
Private:
Int size;
T * data;
Int top;
T * min_data;
T min_value;
Public:
Stack (int size = 100 );
~ Stack ();
T pop ();
// Why do you want to go to the address?
Void push (const T item );
Void print () {cout <min_value <endl ;}
};
Template <class T>
Stack <T>: Stack (int size ){
Data = new T [size];
Min_data = new T [size];
This-> top =-1;
}
Template <class T>
Stack <T> ::~ Stack ()
{
Delete [] data;
Delete [] min_data;
}
Template <class T>
Void Stack <T>: push (const T item)
{
If (top = size-1 ){
Cout <"stack overflow" <endl;
// Return;
}
Top ++;
Data [top] = item;
If (top = 0)
{
Min_data [top] = item;
Min_value = item;
}
Else
{
If (item <min_data [top-1])
{
Min_data [top] = item;
Min_value = item;
}
Else
{
Min_data [top] = min_data [top-1];
This-> min_value = min_data [top-1];
}
}
}
Template <class T>
T Stack <T>: pop ()
{
If (top =-1)
{
Cout <"Empty stack" <endl;
Return-1;
}
T DATA_POP = data [top];
Min_value = min_data [top-1];
Top = top-1;
Return DATA_POP;
}
Int main (){
Int stack_size = 100;
Stack <int> a_value (stack_size );
// Test
A_value.push (10 );
A_value.print ();
A_value.push (2 );
A_value.print ();
A_value.push (3 );
A_value.print ();
A_value.push (1 );
A_value.print ();
A_value.push (5 );
A_value.print ();
Cout <"SC" <endl;
A_value.pop ();
A_value.print ();
A_value.pop ();
A_value.print ();
Return 0;
}