用途: 获取相应位置的元素
定义一个current和index初始都指向第一个节点。
current和index向后移,直到和position相等。然后把current对应节点的data返回即可。
TwoWayLinkList.prototype.get = function (position) {
// 越界判断
if (position < 0 || position >= this.length) { return false }
// 获取元素
var current = this.head
var index = 0
while (index++ < position) {
current = current.next
}
return current.data
}
复制代码
// 测试
var list = new TwoWayLinkList()
list.append('abc')
list.append('bce')
list.append('ghg')
console.log(list.insert(0, 'insert'))
console.log(list.insert(4, 'insert1'))
console.log(list.insert(3, 'insert2'))
console.log(list.toString())
console.log(list.get(2))
其实现在的get()方法的效率并不是很高。比如position为99,那么我们就需要从0一直找到99。对于单向链表只能从头开始找。但是双向链表可以根据就近原则,选择从前往后找,还是从后往前找。
TwoWayLinkList.prototype.get = function (position) {
// 越界判断
if (position < 0 || position >= this.length) { return false }
if (this.length / 2 >= position) {
// 获取元素
var current = this.head
var index = 0
while (index++ < position) {
current = current.next
}
} else {
// 获取元素
var current = this.tail
// 元素的下标只到length-1
var index = this.length - 1
while (index-- > position) {
current = current.prev
}
}
return current.data
}