简体   繁体   中英

Initialize a stack which can find the minimum number. Java

I am using the code like this but there are errors while running... the system returns java.util.EmptyStackException..Can anybody help me?

public class Solution {

    private Stack<Integer> val = new Stack<>();
    private Stack<Integer> stackMin = new Stack<>();
    Integer temp = null;

    public void push(int node) {
        this.val.push(node);
        if(this.stackMin == null){
            this.stackMin.push(node);
        }else if(node<=this.min()){
            this.stackMin.push(node);
        }
    }

    public void pop() {
        if (this.val==null) {
            throw new RuntimeException("Stack is empty.");
        }
        int value = this.val.pop();
        if(value == this.min()){
            this.stackMin.pop();
        }
    }

    public int top() {
        if(this.val!=null){
            return this.val.peek();
        }else{
            throw new RuntimeException("Stack is empty");
        }
    }

    public int min() {
        if(this.stackMin!=null){
            return this.stackMin.peek();
        }
       throw new RuntimeException("Stack is empty");
    }
}

I think that you should use stack.empty() instead of testing for null value. I changed some code and the exception doesn't occur like this.

import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Main m1 = new Main();
        m1.push(2);
        m1.push(1);
        m1.push(3);
        System.out.println(m1.min());
    }
    private Stack<Integer> val = new Stack<>();
    private Stack<Integer> stackMin = new Stack<>();
    Integer temp = null;

    public void push(int node) {
        this.val.push(node);
        if(this.stackMin.empty()){
            this.stackMin.push(node);
        }else if(node<=this.min()){
            this.stackMin.push(node);
        }
    }

    public void pop() {
        if (!this.val.empty()) {
            throw new RuntimeException("Stack is empty.");
        }
        int value = this.val.pop();
        if(value == this.min()){
            this.stackMin.pop();
        }
    }

    public int top() {
        if(!this.val.empty()){
            return this.val.peek();
        }else{
            throw new RuntimeException("Stack is empty");
        }
    }

    public int min() {
        if(!this.stackMin.empty()){
            return this.stackMin.peek();
        }
        throw new RuntimeException("Stack is empty");
    }
}

Test outputs the minimum value

/usr/lib/jvm/java-1.8.0-openjdk-amd64/bin/java Main
1

Process finished with exit code 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM