设计一个具有getMin功能的栈

package com.example.demo;

import java.util.Stack;

/**
 * Created by Administrator on 17.6.1.
 */
public class MyStack {
    private Stack stackData;
    private Stack stackMin;

    public MyStack() {
        stackData = new Stack();
        stackMin = new Stack();
    }


    public void push(int num) {
        if (stackMin.isEmpty()) {
            stackMin.push(num);
        } else if (getMin() > num) {
            stackMin.push(num);
        }
        stackData.push(num);
    }


    public int pop() {
        if (this.stackData.isEmpty()) {
            throw new RuntimeException("stack is empty");
        }
        Integer value = stackData.pop();
        if (value == getMin()) {
            stackMin.pop();
        }

        return value;

    }


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

}

你可能感兴趣的:(设计一个具有getMin功能的栈)