劍指offer---包含min函數的棧(Java)

題目描述

定義棧的數據結構,請在該類型中實現一個能夠得到棧中所含最小元素的min函數(時間複雜度應爲O(1))。

解析思路

在這裏插入圖片描述

實現代碼

import java.util.Stack;

public class Solution {

    Stack<Integer> data = new Stack<Integer>();
    Stack<Integer> min = new Stack<Integer>();
    Integer temp = null;
    public void push(int node) {
        if(temp!=null){
            if(node<=temp){
                data.push(node);
                min.push(node);
                temp = node;
            }else{
                data.push(node);
            }
        }else{
            data.push(node);
            min.push(node);
            temp = node;
        }
    }
    
    public void pop() {
        int num1 = data.pop();
        int num2 = min.pop();
        if(num1!=num2){
            min.push(num2);
        }
    }
    
    public int top() {
        int num1 = data.pop();
        int num2 = min.pop();
        if(num2!=num1){
            min.push(num2);
            return num1;
        }else{
            return num1;
        }
    }
    
    public int min() {
        int num2 = min.pop();
        min.push(num2);
        return num2;
    }
}

運行效果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章