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());
}
}
代碼格式化和刪除語法錯誤。 – Sid
如果回答您的問題,您應該接受使用複選標記的以下答案 –
對不起。我學會了接受答案。我不是很好的英語,但ı學習英語。謝謝 – myvalley