js实现单链表
function linkerList () {
let Node = function (element) {
this.element = element
this.next = null
}
this.length = 0
this.head = null
this.append = function (element) {
let node = new Node(element)
let current
if(this.head === null) {
this.head = node
}else{
current = this.head
while(current.next){
current = current.next
}
current.next = node
}
this.length ++
}
this.removeAt = function (position) {
if (position > -1 && position < this.length) {
let current = this.head,index = 0, previous
if(position === 0 ) {
this.head = current.next
} else {
while(index !== position) {
previous = current
index ++
current = current.next
}
previous.next = current.next
}
this.length --
return current.element
}else {
return null
}
}
this.insert = function (position, element) {
if (position >= 0 && position <= this.length) {
let current = this.head,index = 0,previous,node = Node(element)
if(position === 0) {
node.next = current
head = node
}else{
while(index !== position) {
previous = current
index ++
current = current.next
}
node.next = current
previous.next = node
}
this.length ++
return true
}else{
return false
}
}
this.toString = function(){
let string = ''
let current = this.head
while(current){
string += current.element + (current.next?',':'')
current = current.next
}
return string
}
this.indexOf = function (element) {
let current = head
for (let i = 0;i < this.length;i ++) {
if(element === current.element){
return i
} else {
current = current.next
}
}
return -1
}
this.isEmpty = function () {
return this.length === 0
}
this.size = () => this.length
this.getHead = () => this.head
}