添加到动态数组问题的左侧和右侧

时间:2019-04-14 06:17:08

标签: java arrays dynamic

所以我试图用Java创建一个动态数组。对于这个问题,有一个名为store的主数组,其大小已定义。存储中有一种伪数组,它利用存储块作为动态数组。左变量和右变量是分别用作动态数组的开头和结尾的索引。这意味着left的值是存储区中动态数组开始的索引,而right是结束的位置。

我一直试图为此做addleft和addright方法,但我一直越界错误。但是,我不确定我到底在哪里出错。

    boolean add(int i, int x){
        if (i<0 || i>size) return false;
        if (i<size-i)
            addLeft(i,x);
        else
            addRight(i,x);
        return true;
    }//add
    void addLeft(int i, int x){
        size ++;
        left--;
        if(left == -1) {
            restore();
        }
        for(int j = left; j < left + i; j++) {
            store[j] = store[j+1];
        }
        store[left + 1 + i] = x;
        return;
    }//addLeft
    void addRight(int i, int x){
        size ++;
        right++;
        if(right == CAP+1) {
            restore();
        }
        for(int j = right; j > left + i; j--) {
            store[j] = store[j-1];
        }
        store[left + 1 + i] = x;
        return;
    }//addRight

我正在寻找的结果是输入要在索引处插入的整数,然后向左(对于addleft)或向右(对于addright)的值移动到各自的方向。每当动态数组的一端到达末端时,都可以使用restore()方法扩展存储数组。

1 个答案:

答案 0 :(得分:1)

做了一些数据类型的假设,并用system.out命令替换了您的函数。我在for循环中遇到了异常,因此我认为您的错误是由名为store store[j] = store[j+1];的数组造成的,您的for循环作用域之外的行也超出了边界:store[left + 1 + i] = x;

这是一个有根据的猜测,如果您可以发布完整的代码,我会通过它运行,并希望可以提供更好的答案!不确定变量的大小,左,右,store []和CAP是什么。

更新:

能够在更新addRight方法之后使程序运行。从+1大小的存储中创建了一个临时数组。然后存储克隆温度。这是我关于如何使用addRight方法的想法。

void addRight(int i, int x){
        size++;
        right++;
        if(right == CAP+1) {
            restore();
        }
        int[] temp;
        temp = new int[store.length+1];

        for(int j = 0; j <= store.length; j++) {
            if(j < i){
            temp[j] = store[j];
            }
            else if (j == i) {
            temp[j] = x;
            }
            else if( j > i)
            {
                temp[j] = store[j-1];
            }
        }
        store = new int [temp.length];
        for(int k = 0; k < temp.length; k++)
        {
            store[k] = temp[k];
        }
        return;
相关问题