2016-12-04 120 views
1

我正在學習堆棧數據結構。我想創建一個動態數組。當超過大小時,我想創建一個新的數組。在Java中爲堆棧結構創建動態數組

程序輸出:

java.lang.ArrayIndexOutOfBoundsException: 2 
must be :50 40 30 

的代碼,如下所示:

class Stack{ 
     int array[]; 
     int size; 
     int top; 

     Stack(int size){ 
     this.size=size; 
     array=new int[size]; 
     top=0; 
     } 

     public void push(int a){ 
      if(top>=size){ 
      int array2[]=new int[size*2]; 
      for(int i=0;i<size;i++){ 
      array2[i]=array[i]; 
      } 
      array[top++]=a; 
      } 
      else{ 
      array[top++]=a; 
      } 
     } 
     public int pop(){ 
      return array[--top]; 
     } 
    } 

    public class Stack1 { 

    public static void main(String[] args) { 
     Stack y=new Stack(2); 
     y.push(10); 
     y.push(20); 
     y.push(30); 
     y.push(40); 
     y.push(50); 

     System.out.println(y.pop()); 
     System.out.println(y.pop()); 
     System.out.println(y.pop()); 
    } 
} 
+0

代碼格式化和刪除語法錯誤。 – Sid

+0

如果回答您的問題,您應該接受使用複選標記的以下答案 –

+0

對不起。我學會了接受答案。我不是很好的英語,但ı學習英語。謝謝 – myvalley

回答

1

你正在創建與當原始陣列中充滿了一倍大小的新數組,但你什麼都不做與新陣列。

你的代碼更改爲:

public void push(int a){ 
    if(top>=size){ 
    int array2[]=new int[size*2]; 
    for(int i=0;i<size;i++){ 
     array2[i]=array[i]; 
    } 
    array = array2; 
    size *=2; 
    } 
    array[top++]=a; 
} 
+0

非常感謝你:) – myvalley