【问题标题】:how to remove an element from the end of the array and insert it to the front如何从数组末尾删除一个元素并将其插入到前面
【发布时间】:2018-07-13 10:12:33
【问题描述】:

我正在使用实现数组列表。我想编写一个方法,将最后一个元素插入到前面。到目前为止,我得到了它来获取最后一个元素并将其插入前面,然后将所有内容都转移过来。但是,我似乎无法删除插入到前面的最后一个元素。例如:(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]);
    }
}

【问题讨论】:

  • 你需要使用arraylist吗?
  • 如果该方法总是将最后一个元素放在首位并将所有元素向右移动,为什么它需要任何参数?您可以将其称为rotate() 并将其复制到一个新数组中,它会将旧数组中的最后一个元素复制到新数组的第一个位置,其余元素按顺序复制。

标签: java arrays arraylist data-structures


【解决方案1】:
  • 使用队列
  • 如果你自己想的话,有一个列表开始和结束位置的 2 个整数,而 replaceArray 只是将元素复制到位置结束;然后结束=(结束+1)%容量;开始=(开始+1)%容量; (无需移除 - 无需)

【讨论】:

    【解决方案2】:

    我已经编写了这个实现。我假设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]);
           }
      }
      

    【讨论】:

    • theData是一个数组,int temp = theData;这个语句会导致编译时错误。
    • @ahoxha 错过了。谢谢
    • 你还是搞错了。问题不是将第一个元素放在最后,而是反过来 - 最后一个元素放在首位,其余元素向右移动。此外,temp[theData.length] = first; 将导致 ArrayOutOfBoundsException
    【解决方案3】:
    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);
        }
    }
    

    【讨论】:

      【解决方案4】:
      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));
          }
      
      }
      

      【讨论】:

        【解决方案5】:

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

        这是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, 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-12-02
          • 2016-03-30
          • 2023-01-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-03-22
          相关资源
          最近更新 更多