Create a stack containing the min() function

package  stack;

 

/**

 * 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);

}

}

/**

 * 从栈中取元素

 *

 * 思路:如果数据栈为空,直接返回null

 * 如果数据栈不为空,从数据栈中弹出栈顶元素,并返回

 * 如果最小数据栈的栈顶元素与数据栈弹出的元素相同,那么最小数据栈也要弹出元素

 * @return

 */

public Integer pop(){

if(dataStack.isEmpty()){

return null;

}

Integer data = dataStack.pop();

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

minStack.pop();

}

return data;

}

/**

 * 查看栈的峰值

 * @return

 */

public Integer peek(){

return dataStack.peek();

}

/**

 * 查看栈中的最小元素

 * @return

 */

public Integer min(){

return minStack.peek();

}

/**

 * 主函数

 * @param args

 */

public static void main(String[] args) {

MinStack minStack = new MinStack();

minStack.push(4);

minStack.push(3);

minStack.push(8);

minStack.push(6);

System.out.println("查看栈中的最小元素:");

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

}

}

Guess you like

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