JavaScript鏈表結構——單向鏈表
function LinkList(){
function Node(data){
this.data = data
this.next = null
}
this.head = null
this.length = 0
LinkList.prototype.append = function(data){
let node = new Node(data)
if (this.head == null){
this.head = node
}
else{
let current = this.head
while(current.next != null){
current = current.next
}
current.next = node
}
this.length += 1
}
LinkList.prototype.toString = function(){
let current = this.head
let listString = ''
while(current != null){
listString += current.data + ' '
current = current.next
}
return listString
}
LinkList.prototype.insert = function(data, position){
let node = new Node(data)
if (position < 0 || position > this.length){
return false
}
else if (position == 0){
node.next = this.head
this.head = node
}
else{
let index = 0
let current = this.head
let previous = null
while(index < position){
previous = current
current = current.next
index ++
}
previous.next = node
node.next = current
}
this.length += 1
}
LinkList.prototype.get = function(position){
if (position < 0 || position >= this.length){
return null
}
let current = this.head
let index = 0
while(index < position){
current = current.next
index ++
}
return current.data
}
LinkList.prototype.indexOf = function(data){
let current = this.head
let index = 0
while(current != null){
if(current.data == data){
return index
}
current = current.next
index ++
}
return -1
}
LinkList.prototype.update = function(newData, position){
if (position < 0 || position >= this.length){
return false
}
let current = this.head
let index = 0
while(index < position){
current = current.next
index ++
}
console.log(current.data + '=>' + newData)
current.data = newData
}
LinkList.prototype.removeAt = function(position){
if (position < 0 || position >= this.length){
return null
}
else if(position == 0){
this.head = this.head.next
}
else{
let current = this.head
let previous = null
let index = 0
while(index < position){
previous = current
current = current.next
index ++
}
previous.next = current.next
}
this.length --
}
LinkList.prototype.remove = function(data){
let index = this.indexOf(data)
return this.removeAt(index)
}
}