Question: To define the stack data structure, 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 ).
Analysis: the main limitation of this question is that the time complexity is O (1). First of all, we must consider changing the space for time. Here we will give each element in the stack. If it is the smallest element, we will let it point to the domain of the last smallest element. This will be easy to implement.
The following code is used:
View Code # pragma once
Template <typename T>
Class stack;
Template <typename T>
Class stack_node
{
Friend class stack <T>;
Private:
T data;
Int smin; // if the current node is the smallest node, it points to the minimum node position before the node is pushed.
};
Template <typename T>
Class stack
{
Public:
Stack (int size = 10)
{
This-> size = size;
A = new stack_node <T> [size];
Top =-1;
Min_index =-1;
}
~ Stack ()
{
Delete [];
}
Bool is_empty ()
{
If (top =-1)
Return true;
Else
Return false;
}
Bool is_full ()
{
If (top = size-1)
Return true;
Else
Return false;
}
T min ()
{
If (is_empty ())
Throw "stack is empty ";
Return a [min_index]. data;
}
Void push (T data)
{
If (is_full ())
Throw "stack is full ";
Top ++;
A [top]. data = data;
If (min_index =-1 | a [min_index]. data> data)
{
A [top]. smin = min_index;
Min_index = top;
}
}
T pop ()
{
If (is_empty ())
Throw "stack is empty ";
If (top = min_index)
Min_index = a [top]. smin;
Return a [top --]. data;
}
T peek ()
{
If (is_empty ())
Throw "stack is empty ";
Return a [top];
}
Private:
Stack_node <T> *;
Int top;
Int min_index;
Int size;
};
Test code
View Code # include "stack. h"
# Include <iostream>
Using namespace std;
Int main ()
{
Stack <int> s (20 );
S. push (10 );
Cout <s. min () <endl;
S. push (1, 100 );
Cout <s. min () <endl;
S. push (3 );
Cout <s. min () <endl;
S. push (20 );
Cout <s. min () <endl;
S. push (17 );
Cout <s. min () <endl;
S. pop ();
Cout <s. min () <endl;
S. pop ();
Cout <s. min () <endl;
S. pop ();
Cout <s. min () <endl;
S. pop ();
Cout <s. min () <endl;
Return 0;
}