简体   繁体   English

在 Java 中为堆栈结构创建动态数组

[英]Create a Dynamic Array for Stack structure in Java

I am learning the Stack Data Structure.我正在学习堆栈数据结构。 I want to create a dynamic array.我想创建一个动态数组。 When the size is exceeded, I want to create a new array.当超过大小时,我想创建一个新数组。

Program output:程序输出:

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

The code is as given below:代码如下:

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

You are creating a new array with a doubled size when the original array is full, but then you do nothing with the new array.当原始数组已满时,您正在创建一个大小加倍的新数组,但随后您对新数组什么也不做。

Change your code to :将您的代码更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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