题目要求:
/**
* 第一道题目:实现一个栈,在实现栈功能的基础上,在实现返回栈中最小的元素的操作
* 要求:
* ①pop,push,getMin操作的时间复杂度都是O(1)
* ②设计的栈类型可以使用现成的栈结构
代码实现
package com.isea.brush;
import java.util.Stack;
/**
* 第一道题目:实现一个栈,在实现栈功能的基础上,在实现返回栈中最小的元素的操作
* 要求:
* ①pop,push,getMin操作的时间复杂度都是O(1)
* ②设计的栈类型可以使用现成的栈结构
*
* 解题思路
*/
public class MyStack<T extends Comparable> {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public MyStack() {
stackData = new Stack<Integer>();
stackMin = new Stack<Integer>();
}
/**
* 入栈操作
*
* @param num
*/
public void push(Integer num) {
stackData.push(num);
if (stackMin.isEmpty()) { // 如果stackMin中为空,直接往里面添加元素
stackMin.push(num);
} else { // 如果stackMin中不为空,则判断当前元素和stackMin栈顶的元素的大小,将较小的元素添加到栈中
stackMin.push(num < stackMin.peek() ? num : stackMin.peek());
}
}
/**
* 出栈操作
*
* @return
*/
public int pop() {
if (stackData.isEmpty()) {
throw new IllegalArgumentException("The stack is empty...");
}
stackMin.pop();
return stackData.pop();
}
/**
* 获取栈中的最小值
* @return
*/
public int getMin(){
if (stackData.isEmpty()){
throw new IllegalArgumentException("The stack is empty...");
}
return stackMin.peek();
}
public static void main(String[] args) {
MyStack<Integer> stack = new MyStack<Integer>();
int[] arr = {3,5,8,2,4,2};
for (int i = 0; i < arr.length; i++) {
stack.push(arr[i]);
}
for (int i = 0; i < arr.length - 1; i++) {
stack.pop();
System.out.println(stack.getMin());
}
}
}