2017-06-03 33 views
0

我正在使用這樣的代碼,但運行時出現錯誤......系統返回java.util.EmptyStackException..Can任何人都可以幫助我?初始化可以找到最小數量的堆棧。 Java

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"); 
    } 
} 
+0

在什麼叫你得到這個異常? – Mureinik

+0

找到錯誤...我應該使用isEmpty()來檢查堆棧是否爲空... – Akrisllen

回答

0

我認爲你應該使用stack.empty()而不是測試空值。我改變了一些代碼,異常不會像這樣發生。

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"); 
    } 
} 

測試輸出最小值

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

Process finished with exit code 0 
相關問題