- get实现 -- 获取指定位置元素值
- indexOf实现 -- 返回指定值位置
- update实现 -- 修改指定位置值
- removeAt方法实现 -- 删除指定位置元素
- remove实现 -- 移除指定值
- 总结
代码
// 5 get方法
linkedList.prototype.get = function(position){
// 1 越界判断 -- 有关位置都要判断越界
if(position < 0 || position >= this.length) return null;
// 2 获取对应的数据
let current = this.head;
let index = 0;
while(index++ < position){
current = current.next;
}
return current.data;
}
indexOf实现 – 返回指定值位置
代码
// 6 indexOf方法
linkedList.prototype.indexOf = function(data){
// 1 定义变量
let current = this.head;
// 记录返回位置
let index = 0;
// 2 开始查找
while(current){
if(current.data === data){
return index;
}
current = current.next;
index += 1;
}
// 没有找到返回-1
return -1;
}
update实现 – 修改指定位置值
代码
// 7 update方法
linkedList.prototype.update = function(position,newData){
// 1 判断越界
if(position < 0 || position >= this.length) return false;
// 2 查找正确的节点
let current = this.head;
let index = 0;
while(index++ < position){
current = current.next;
}
// 3 将position上的data修改
current.data = newData;
return true;
}
removeAt方法实现 – 删除指定位置元素
视频代码
视频的代码思路更加清晰,因为保存了两个节点的数据,更好理解!我的代码就是我自己上次写插入的思路,可以只用一个变量保存,但是因为我这个没有保存删除的节点的信息,所以无法像视频一样返回节点的数据!
我的代码
// 8 removeAt方法
linkedList.prototype.removeAt = function(position){
if(position < 0 || position >= this.length) return false;
if(position === 0){
this.head = this.head.next;
}else{
let current = this.head;
let index = 0;
while(index++ < position-1){
current = current.next;
}
current.next = current.next.next;
}
// 注意length
this.length -= 1;
return true;
}
remove实现 – 移除指定值
代码
// 9 remove方法
linkedList.prototype.remove = function(data){
// 获取位置
let num = this.indexOf(data);
// 删除
this.removeAt(num);
}
这里菜鸟就不写剩下的isEmpty和size了,毕竟有了length,这两个就是小儿科!
总结理解了链表之后,发现写链表的操作其实也还算比较简单,值得注意的就是current指向的谁你得搞得很清楚(就是while循环得搞清楚执行了多少次),基本上所有的操作就是靠current的移动来完成的,还有你给定的位置和操作次数的关系也要搞清楚,其和数组一样是从0开始,感觉真的和数组很像!



