用途: 根据data找到其位置。
思路: 定义current不断向下查找,用index记录索引值。对比current的data和我们传入的参数data,如果相等,把index返回。
TwoWayLinkList.prototype.indexOf = function(data){
// 1.定义变量
var current = this.head
var index = 0
// 2.查找和data相同的节点。
while(current){
if(current.data==data){
return index
}else{
current=current.next;
index+=1
}
}
return -1
}
复制代码
// 测试
var list = new TwoWayLinkList();
list.append('abc');
list.append('bce');
list.append('ghg');
console.log(list.indexOf('bce'));
用途: 更改指定位置的元素为传进来的元素。
思路: 定义current变量,向下寻找,找到节点后那,把这个节点的data更改为我们传进来的。
current = current.next
也就是向下寻找。index++<position
在与position比较的同时,还在递增。 // update
TwoWayLinkList.prototype.update = function (position,newData){
// 越界判断
if(position<0 || position>=this.length) return false
// 寻找正确节点
var current = this.head
var index = 0
while(index++<position){
current = current.next
}
// 修改找到的节点信息
current.data = newData
return true
}
复制代码
var list = new TwoWayLinkList();
list.append('abc');
list.append('bce');
list.append('ghg');
console.log(list.update(0,'sdsds'));
console.log(list.update(2,'ss'));
console.log(list.toString())
如下,list本来是 'abc bce ghg'
。