剑指offer--第30题 包含min函数的栈

第30题 包含min函数的栈

题目: 定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数。
解题思路 尴尬完全懵逼的没有看懂题目的意思,最后是参看了剑指offer的解题思路写的代码。
剑指offer的解题思路
建立一个辅助栈,保存当前数据栈的最小值和次小值。

自己写的low代码

import java.util.Stack;

public class Solution {

   //数据栈;
	 private  Stack<Integer> data_stack = new Stack();
	 //辅助栈;
	 private Stack<Integer> min_stack = new Stack();
    public void push(int node) { 
     data_stack.push(node);
     if(!min_stack.isEmpty()) {
    	if( min_stack.peek()>node) {
    		min_stack.push(node);
    	}else {
    		min_stack.push(min_stack.peek());
    	}
     }else {  //需要考虑这个地方;
    	 min_stack.push(node);
     }
    }
    
    public void pop() {
        if(!data_stack.isEmpty()) {
        	data_stack.pop();
        	min_stack.pop();
        	
        }
    }
    
    public int top() {
        return data_stack.peek();
    }
    
    public int min() {
        return min_stack.peek();
    }
}
多思考,多尝试。
原文地址:https://www.cnblogs.com/LynnMin/p/9285599.html