如何从数组末尾删除元素并将其插入前面

时间:2018-02-02 20:47:27

标签: java arrays arraylist data-structures

我正在使用实现arraylist。我想编写一个方法,它接受最后一个元素并将其插入前面。到目前为止,我得到它采取最后一个元素并将其插入前面,并将一切都移过来。但是,我似乎无法删除前面插入的最后一个元素。例如:(1,2,5)到(5,1,2)但我得到了(5,1,2,5)。我在replaceArray()方法中遗漏了一些东西,但我真的不知道是什么。谢谢你的帮助。

班级的构造函数:

public KWArrayList() {
    capacity = INITIAL_CAPACITY;
    theData = (E[]) new Object[capacity];
}

public void replaceArray(int index, E anElement) {
    for (int i = size; i > index; i--){
        theData[i] = theData[i - 1];
    }

    theData[index] = anEntry;

    size--;

    for (int i = 0; i < theData.length; i++){
        System.out.println(theData[i]);
    }
}

5 个答案:

答案 0 :(得分:1)

我会使用这种旋转数组的简单方法(我认为该方法应该被称为rotate而不是replaceAll,因为它实际上将数组旋转了一个位置。) / p>

这是方法rotate()

@SuppressWarnings("unchecked")
public void rotate() {
    Object[] temp = new Object[theData.length];
    //copy each element, except the first, from theData into temp by shifting one position off to the right
    for (int i = temp.length - 1; i > 0; i--) {
        temp[i] = theData[i - 1];
    }
    //move the last element into the first position
    temp[0] = theData[theData.length - 1];
    //update theData
    theData = (T[]) temp;
}

完整的可测试示例

public class MyArrayList<T> {
    int INITIAL_CAPACITY = 10;
    int capacity;
    T[] theData;

    @SuppressWarnings("unchecked")
    public MyArrayList() {
        capacity = INITIAL_CAPACITY;
        theData = (T[]) new Object[capacity];
    }

    @SuppressWarnings("unchecked")
    public MyArrayList(int capacity) {
        this.capacity = capacity;
        theData = (T[]) new Object[this.capacity];
    }

    @SuppressWarnings("unchecked")
    public void rotate() {
        Object[] temp = new Object[theData.length];
        //copy each element, except the first, from theData into temp by shifting one position off to the right
        // to the right
        for (int i = temp.length - 1; i > 0; i--) {
            temp[i] = theData[i - 1];
        }
        // move the last element into the first position
        temp[0] = theData[theData.length - 1];
        // update theData
        theData = (T[]) temp;
    }

    /**
     * For testing purposes only. It doesn't handle out of bounds values of
     * index.
     */
    private void insert(T t, int index) {
        theData[index] = t;
    }

    public void print() {
        for (T t : theData) {
            System.out.print(t + ", ");
        }
        System.out.println();
    }

    @SafeVarargs
    public static <E> MyArrayList<E> of(E... elements) {
        MyArrayList<E> m = new MyArrayList<>(elements.length);
        for (int i = 0; i < elements.length; i++) {
            m.insert(elements[i], i);
        }
        return m;
    }
}

测试rotate()方法:

public class TestMyArrayList {
    public static void main(String[] args) {
        MyArrayList<Integer> m = MyArrayList.of(1, 2, 3, 4, 5);
        m.print();
        m.rotate();
        m.print();
    }
}

它会打印出来:

1, 2, 3, 4, 5, 
5, 1, 2, 3, 4, 

答案 1 :(得分:0)

我写过这个实现。我假设theData的类型为int,但您可以将其更改为任何内容。我也删除了函数中的参数,因为我不使用它们。

  1. 首先,我们将数组复制到temp变量。

  2. 其次,我们将theData中的第一个值保存到另一个临时变量中。

  3. 然后我们开始从theData开始转换到第二个到最后一个索引。

  4. 最后,我们将从theData保存的第一个索引复制到first并将其分配给数组的最后一个索引。

  5. 打印

    public void replaceArray() {
         int [] temp = theData;
         int last = theData[theData.length - 1];
         for (int i = theData.length - 1; i > 0; i--){
             temp[i] = theData[i - 1];
         }
    
         temp[0] = last;
    
         for (int i = 0; i < theData.length; i++){
             System.out.println(temp[i]);
         }
    }
    

答案 2 :(得分:0)

import java.util.Arrays;

public class KWArrayList <E>{
    private E[] data; /* your list */
    private int nbElt = 0; /* nb of element in your list */
    /* no need to store the capacity since data.length give it */
    KWArrayList(int capacity){
        data = (E[]) new Object[capacity]; /* create */
    }

    private void resize() {
        E[] tmp = (E[]) new Object[2 * data.length]; /* if the number of element >= capacity you double the capacity and copy old elt */
        data = Arrays.copyOf(data, 2 * data.length);
    }

    public void add(E elt) {
        if(nbElt >= data.length) {
            resize();
        }
        data[nbElt++] = elt; /* add an elt */
    }

    public void add(E ... elt) { /* add multiple elt */
        for(E e : elt) {
            add(e);
        }
    }

    public E removeLast() { /* remove the last elt and return it */
        if(nbElt == 0) {
            throw new IllegalStateException("nothing to remove");
        }
        return data[--nbElt];
    }

    public void removeLastAndInsertFront() {
        data[0] = removeLast();
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        if(nbElt == 0) {
            return sb.append("]").toString();
        }
        for(int i = 0; i < nbElt; i++) {
            sb.append(data[i]).append(", ");
        }
        sb.setLength(sb.length() - 2);
        return sb.append("]").toString();
    }

    public static void main(String[] args) {
        KWArrayList<Integer> data = new KWArrayList(1);
        data.add(1, 2, 5);
        System.out.println(data);
        System.out.println("first delete");
        data.removeLastAndInsertFront();
        System.out.println(data);
        System.out.println("second delete");
        data.removeLastAndInsertFront();
        System.out.println(data);
        System.out.println("third delete");
        data.removeLastAndInsertFront();
        System.out.println(data);
    }
}

答案 3 :(得分:0)

public class MyArrayList extends ArrayList<Object>{

    public void rotateRight(){
        this.add(0, this.remove(this.size()-1));
    }
    public void rotateLeft(){
        this.add(this.remove(0));
    }

}

答案 4 :(得分:-3)

  • 使用队列
  • 如果你是自己的,那么列表的开头和结尾的位置有2个整数,而replaceArray只是将元素复制到位置结束;然后结束=(结束+ 1)%容量;开始=(开始+1)%容量; (不删除 - 不需要)