剑指offer---包含min的栈

思路:该题主要是补充栈的min方法,例如:栈有pop、push、peek等内置方法,每次调用这些方法就能返回个结果或者有个响应,本题意在补充min方法,使得每次调用min方法都能得到栈中最小值,保证每次执行过min()函数后栈中元素不变。

push(6),min()返回6;push(7), min()返回6,push(2),min()返回2..........

public class Solution {
  Stack<Integer> stack = new Stack<Integer>();
  public void push(int node) {
    stack.push(node);
  }
  public void pop() {
    stack.pop();
  }
  public int top() {
    return stack.peek();
  }
  public int min() {
    Stack<Integer> st = new Stack<Integer>();
    int min = stack.pop();
    st.push(min);
    while(!stack.isEmpty()){
      int temp = stack.pop();
      if(temp < min){
        min = temp;
      }
      st.push(temp);
    }
    while(!st.isEmpty()){
      stack.push(st.pop());
    }
    return min;
  }
}

原文地址:https://www.cnblogs.com/huaiyinxiaojiang/p/6613045.html