13. Stack containing min function

subject

To define the data structure of the stack, please implement a min function (time complexity should be O(1)) in this type that can obtain the minimum elements contained in the stack.

Train of thought

1. Define two stacks, one stack is used to store data and the other stack is used to store the minimum value of the stack each time data is pushed into the stack.

2. Each time data is pushed into the stack, the data is compared with the top element of the minimum stack, and the smaller value compared between the two is stored into the minimum stack again.

4. The data stack is pushed out, and the minimum stack is pushed out.

3. The top of the minimum stack is always the minimum of the current stack.

Code

var dataStack = [];
var minStack = [];

function push(node)
{
dataStack.push(node);
if(minStack.length === 0 ||  node < min()){
minStack.push(node);
}else{
minStack.push(min());
}
}
function pop()
{
minStack.pop();
return dataStack.pop();
}
function top()
{
var length = dataStack.length;
return length>0&&dataStack[length-1]
}
function min()
{
var length = minStack.length;
return length>0&&minStack[length-1]
}