zoukankan      html  css  js  c++  java
  • 包含min函数的栈

    题目描述:定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

    实现语言:Java

    import java.util.Stack;
    
    public class Solution {
        Stack<Integer> s=new Stack<Integer>();
        Stack<Integer> m=new Stack<Integer>();
        
        public void push(int node) {
            s.push(node);
            if(m.isEmpty()){
                m.push(node);
            }else if(m.peek()>node){
                m.push(node);
            }else{
                m.push(m.peek());
            }
        }
        
        public void pop() {
            s.pop();
            m.pop();
        }
        
        public int top() {
            return s.peek();
        }
        
        public int min() {
            return m.peek();
        }
    }
    

     实现语言:Java

    import java.util.Stack;
    
    public class Solution {
        Stack<Integer> s=new Stack<Integer>();
        Stack<Integer> m=new Stack<Integer>();
        
        public void push(int node) {
            s.push(node);
            if(m.isEmpty()){
                m.push(node);
            }else if(m.peek()>node){
                m.push(node);
            }
        }
        
        public void pop() {
            if(s.peek()==m.peek()){
                m.pop();
            }
            s.pop();
        }
        
        public int top() {
            return s.peek();
        }
        
        public int min() {
            return m.peek();
        }
    }
    
  • 相关阅读:
    自介
    打招呼
    试验四
    作业:实验二
    个人简介
    实验4
    构建之法—心得体会
    作业:实验二
    个人简介
    软件测试第四次博客作业2
  • 原文地址:https://www.cnblogs.com/xidian2014/p/10197350.html
Copyright © 2011-2022 走看看