20、包含min函数的栈

题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

import java.util.Stack;

public class Solution {

    //数据栈
    Stack<Integer> s1 = new Stack<>();
    
    //辅助栈
    Stack<Integer> s2 = new Stack<>();
    
    public void push(int node) {
        s1.push(node);
        if(s2.isEmpty()){
            s2.push(node);
        }else if(node<s2.peek()){
            s2.push(node);
        }else{
            s2.push(s2.peek());
        }
    }
    
    public void pop() {
        s1.pop();
        s2.pop();
    }
    
    public int top() {
      
        return s1.peek();
    }
    
    public int min() {
        return s2.peek();
    }
}

2017.6.1 第二次做,思路略有变化

import java.util.Stack;

public class Solution {

    Stack<Integer> stack1 = new Stack<>();
    Stack<Integer> stack2 = new Stack<>();
    
    public void push(int node) {
        stack1.push(node);
        if(stack2.isEmpty()){
            stack2.push(node);
        }else if(stack2.peek()>node){
              stack2.push(node);  
        }
    }
    
    public void pop() {
        if(stack1.peek()==stack2.peek()){
            stack1.pop();
            stack2.pop();
        }else{
            stack1.pop();
        }
    }
    
    public int top() {
        
         return stack1.peek();
        
    }
    
    public int min() {
        
            return stack2.peek();
    }
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容