Java中的堆栈和动态数组实现

时间:2014-11-04 11:20:16

标签: java

我需要使用动态数组实现堆栈数组,我必须自己创建。

这是我的动态数组:

import java.util.Arrays;

public class Array {
public int[] dynArray; 
int counter = 0;  

public void create(int n) {
    dynArray = new int[n]; 
}


public void doubleSize() {
    int currentSize = dynArray.length; 
    int newSize = currentSize*2; 
    dynArray = Arrays.copyOf(dynArray, newSize);    
}


private void halfSize() {
    int currentSize = dynArray.length; 
    int newSize = currentSize/2;    
    dynArray = Arrays.copyOf(dynArray, newSize);
}

public void add(int x) {
    dynArray[counter] = x; 
    counter++; 

    float ratio = (float) counter / (float) dynArray.length;
    if (ratio == 1) {
        doubleSize(); 
    }
}

public int rem() {
    int last = dynArray[counter-1]; 
    dynArray[counter-1] = 0; 
    counter--; 


    float ratio = (float) counter / (float) dynArray.length;
    if (ratio <= 0.25) {
        halfSize();
    }
    return last;
}

public int get(int i) {

    if(!(check(i))) {
        //System.out.print("Cannot be added");
        return i;
    }
    else return dynArray[i]; 
}


public void put(int x, int y) {

    float ratio = (float) counter / (float) dynArray.length;
    if (ratio ==1) {
        doubleSize(); 
    }
    if(!check(y)) {
        System.out.println("No such index, nothing added to "+y);
    } else {
        dynArray[y] = x; 
    }
}

public int len() {
    return dynArray.length;
}


public boolean check(int index) {
    if(index <0 || index >=dynArray.length) {
        return false;
    } else {
        return true;
    }
}

public static void main(String[] args) {
    Array dm = new Array();
    dm.create(5);
    System.out.println("Current array length "+dm.len());
    dm.add(5);
    dm.add(4);
    dm.add(3);
    dm.add(1);
    dm.add(2);
    System.out.println("Current array length "+dm.len());
    dm.rem();
    dm.rem();
    System.out.println("Current array length "+dm.len());
    dm.rem();
    System.out.println("Current array length "+dm.len());
    dm.rem();
    System.out.println("Current array length "+dm.len());
 }
 }

这是我的堆栈代码:

public class Stack {
private static Array a;

public void create() {
    a = new Array();
}


void push(int x) {
    a.add(x);
}


int pop() {
    return a.rem();
}


boolean isEmpty() {
    return a.len() == 0;
}

public static void main(String[] args) {
    Stack stack = new Stack();
    stack.create();
    stack.push(1);
    /*int k = 1;
    stack.push(2*k);
    stack.push(2*k+1);
    stack.push(2*k+2);

    for (int i = 0; i<40; i++) {
        System.out.println(stack.pop());
    }*/

}
}

当我在stack.push(1) main中写Stack.java时,它会在NullPointerException行显示a.add(x)。我不明白为什么会发生这种异常。

1 个答案:

答案 0 :(得分:2)

Stack中的创建方法会创建一个新的Array实例,但不会调用Array的创建方法。因此,dynArray保持为空,并且在访问NullPointerException时获得dynArray[counter] = x;

您应该在create的构造函数中调用Array(或者消除create方法并将其代码移动到构造函数中)。