顺序表中的元素移动

来源:互联网 发布:js开发桌面应用程序 编辑:程序博客网 时间:2024/04/27 21:24

// 移去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] 的值相等了,

只不过最后没有显示罢了

原创粉丝点击