链表结构的封装
function LinkedList(){
function Node(data){
this.data = data
this.next = null
}
this.head = null
this.length = 0
}
实现链表常见操作
追加append方法
- 如果是就将
head指向这个节点
- 如果不是就用
while找到最后一个节点
LinkedList.prototype.append = function (data) {
var newNode = new Node(data)
if(this.length == 0){
this.head = newNode
}else{
var current = this.head
while(current.next){
current = current.next
}
current.next = newNode
}
this.length += 1
}
toString方法
LinkedList.prototype.toString = function () {
var current = this.head
var listString = ''
while(current){
listString += current.data + ' '
current = current.next
}
return listString
}
insert插入方法
LinkedList.prototype.insert = function (position, data) {
if (position < 0 || position > this.length) return false
var newNode = new Node(data)
var previous = null
var current = this.head
if (position == 0) {
newNode.next = this.head
this.head = newNode
} else {
var index = 0
while (index++ < position) {
previous = current
current = current.next
}
newNode.next = current
previous.next = newNode
}
this.length += 1
return true
}