您的位置:首页 > 其它

顺序表中的元素移动

2011-04-17 16:29 127 查看
// 移去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] 的值相等了,

只不过最后没有显示罢了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐