スタック内の最小要素を返す機能を備えたスタック構造を実現


特殊なスタックを実現し、スタックの基本機能を実現した上で、スタックに戻る最小要素の操作要求を実現する:pop、push、getMin操作の時間複雑度はすべてO(1)である.
バージョン1
package com.chanmufeng.codingInterviewGuide;

import java.util.Stack;

public class GetMinStack1 {
    private static Stack dataStack = new Stack<>();
    private static Stack minStack = new Stack<>();

    public static void push(int newNum) {
        dataStack.push(newNum);
        if (minStack.isEmpty()) {
            minStack.push(newNum);
        } else {
            minStack.push(Math.min(minStack.peek(), newNum));
        }
    }

    public static int pop() {
        if (dataStack.isEmpty()) {
            throw new RuntimeException("stack is empty");
        }
        minStack.pop();
        return dataStack.pop();
    }

    public static int getMin() {
        if (minStack.isEmpty()) {
            throw new RuntimeException("stack is empty");
        }
        return minStack.peek();
    }

    public int size() {
        return dataStack.size();
    }


    public static void main(String[] args) {
        GetMinStack1 stack = new GetMinStack1();
        stack.push(3);
        stack.push(4);
        stack.push(5);
        stack.push(1);
        stack.push(2);
        stack.push(1);

        while (stack.size()>0){
            System.out.println(stack.getMin());
            stack.pop();
        }
    }
}

バージョン2
package com.chanmufeng.codingInterviewGuide;

import java.util.ArrayList;
import java.util.Stack;

/**
 *                   
 *    ,  minStack     
 */
public class GetMinStack2 {
    private static ArrayList dataStack = new ArrayList<>();
    private static Stack minStack = new Stack<>();

    public static void push(int newNum) {
        dataStack.add(newNum);
        if (minStack.isEmpty() || getMin() > newNum) {
            minStack.push(dataStack.size() - 1);
        }
    }

    public static int pop() {
        if (dataStack.isEmpty()) {
            throw new RuntimeException("stack is empty");
        }
        int size = dataStack.size();
        int res = dataStack.remove(--size);

        //           minStack     ,   
        if (minStack.peek() == size) {
            minStack.pop();
        }
        return res;
    }

    public static int getMin() {
        if (minStack.isEmpty()) {
            throw new RuntimeException("stack is empty");
        }
        return dataStack.get(minStack.peek());
    }

    public int size() {
        return dataStack.size();
    }


    public static void main(String[] args) {
        GetMinStack2 stack = new GetMinStack2();
        stack.push(3);
        stack.push(4);
        stack.push(5);
        stack.push(1);
        stack.push(2);
        stack.push(1);

        while (stack.size() > 0) {
            System.out.println(stack.getMin());
            stack.pop();
        }
    }
}