Create a stack containing the min() function

package 栈;

 

/**

 * Design a stack with the smallest function min (), requiring the time complexity of min , push, and pop to be O(1)

 *

 * Idea: Use the data stack and the minimum data stack to simulate a stack with the minimum function min (), where the minimum data stack stores the minimum element in the data stack

 *

 * @author LiZhe

 */

public class  MinStack { 

Stack dataStack  = new  Stack(); //Define the stack for storing data

Stack minStack  = new  Stack(); //Define the stack that stores the smallest data

/**

 * adding data

 *

 * Idea: First add data to the data stack, and then judge whether the minimum data stack is empty, if it is empty, or the peak value in the minimum data stack is larger than the newly added element,

 * also add the new element to the minimal stack

 * @param data

 */

publicvoid push(intdata){  

dataStack.push(data);

if(minStack.isEmpty() || minStack.peek()>data){

minStack.push(data);

}

}

/**

 * Get element from stack

 *

 * Idea: If the data stack is empty, return null directly

 * If the data stack is not empty, pop the top element from the data stack and return

 * If the top element of the smallest data stack is the same as the element popped from the data stack, then the smallest data stack will also pop the element

 * @return

 */

public Integer pop(){

if(dataStack.isEmpty()){

returnnull; 

}

Integer data = dataStack.pop();

if(data == minStack.peek()){

minStack .pop ();

}

returndata; 

}

/**

 * View the peak value of the stack

 * @return

 */

public Integer peek(){

returndataStack.peek(); 

}

/**

 * View the smallest element in the stack

 * @return

 */

public Integer min(){

returnminStack.peek(); 

}

/**

 * main function

 * @param args

 */

publicstaticvoid main(String[] args) {  

MinStack minStack  = new  MinStack ();

minStack .push (4);

minStack .push (3);

minStack .push (8);

minStack .push (6);

System.out .println ( "Check the smallest element in the stack: " );

System. out .println ( minStack .min ());

}

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326049035&siteId=291194637