Javascript 手写单向链表
function LinkedList_oneWay() {
this.head = null
this.length = 0
function Node(element,next=null) {
this.element = element
this.next = next
}
LinkedList_oneWay.prototype.append = function(element) {
let node = new Node(element)
if (this.head === null) {
this.head = node
}else {
let node1 = this.head
while (node1.next !== null){
node1 = node1.next
}
node1.next = node
}
this.length++
}
LinkedList_oneWay.prototype.insert = function(element,position) {
let node = new Node(element)
let node1 = this.head
for (let i=0; i< position - 1; i++) {
node1 = node1.next
}
node.next = node1.next
node1.next = node
this.length ++
}
LinkedList_oneWay.prototype.get = function(position) {
if (position >= this.length) {
return null
}
let node1 = this.head
for (let i=0; i< position; i++) {
node1 = node1.next
}
return node1.element
}
LinkedList_oneWay.prototype.indexOf = function(element) {
let index = 0
let node1 = this.head
while (index<this.length) {
if (node1.element === element) {
return index
}
node1 = node1.next
index ++
}
return -1
}
LinkedList_oneWay.prototype.update = function(element,position) {
if (position >= this.length) {
return null
}
let node1 = this.head
for (let i=0; i< position; i++) {
node1 = node1.next
}
node1.element = element
}
LinkedList_oneWay.prototype.removeAt = function(position) {
if (position >= this.length) {
return null
}
let node1 = this.head
for (let i=0; i< position-1; i++) {
node1 = node1.next
}
let element = node1.next.element
node1.next = node1.next.next
this.length --
return element
}
LinkedList_oneWay.prototype.remove = function(element) {
let node1 = this.head
let index = 0
if (node1.element === element) {
this.head = node1.next
return index
}
while(node1 !== null) {
index ++
if (node1.next.element === element) {
node1.next = node1.next.next
return index
}
node1 = node1.next
}
return -1
}
LinkedList_oneWay.prototype.isEmpty = function() {
return this.head === null ? true : false
}
LinkedList_oneWay.prototype.size = function() {
return this.length
}
LinkedList_oneWay.prototype.toString = function() {
let node1 = this.head
let arr = []
while (node1 !== null) {
arr.push(node1.element)
node1 = node1.next
}
return arr.join(',')
}
}