顺序表中的元素移动

    技术2022-05-20  37

    // 移去index位置的对象,若操作成功,则返回被移去对象,否则返回null public E remove(int index) {  if (this.n != 0 && index >= 0 && index < this.n) {   E old = (E) this.table[index];   for (int j = index; j < this.n - 1; j++) { // 元素前移,平均移动n/2    this.table[j] = this.table[j + 1];   }//   System.out.println(this.table[this.n - 1]);   this.table[this.n - 1] = null;   this.n--;   return old; // 若操作成功,则返回被移去对象  }  return null; // 未找到删除对象,操作不成功,,返回null }

     

    我认为,这里的元素移动实际上是复制加覆盖的,所以要加上这个this.table[this.n - 1] = null;,否则的话this.table[this.n - 1] 还是原来的值,(在this.n--语句执行之前)现在就与this.table[this.n - 2] 的值相等了,

    只不过最后没有显示罢了


    最新回复(0)