Javascript 手写双向链表
代码如下
function LinkedList_twoWay() {
this.head = null
this.tail = null
this.length = 0
function Node(element,next=null,prev=null) {
this.element = element
this.next = next
this.prev = prev
}
LinkedList_twoWay.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
node.prev = node1
}
this.tail = node
this.length++
}
LinkedList_twoWay.prototype.insert = function(element,position) {
if (position > this.length) {
return null
}
let node1 = this.head
for (let i=0; i< position; i++) {
node1 = node1.next
}
let node = null
if (position === this.length) {
this.append(element)
return
}else {
node = new Node(element)
node.next = node1
}
if (position === 0) {
this.head = node
}else {
node.prev = node1.prev
node1.prev.next = node
}
node1.prev = node
this.length++
}
LinkedList_twoWay.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_twoWay.prototype.indexOf = function(element) {
let node1 = this.head
let index = 0
while (index < this.length) {
if (node1.element === element) {
return index
}
node1 = node1.next
index++
}
return -1
}
LinkedList_twoWay.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_twoWay.prototype.removeAt = function(position) {
if (position >= this.length) {
return null
}
let node1 = this.head
for (let i=0; i< position; i++) {
node1 = node1.next
}
let element = node1.element
if (position === 0) {
this.head = node1.next
}else {
node1.prev.next = node1.next
}
if (position !== this.length - 1){
node1.next.prev = node1.prev
}
this.length--
return element
}
LinkedList_twoWay.prototype.remove = function(element) {
let node1 = this.head
let index = 0
while (index < this.length) {
if (node1.element === element) {
if (index === 0) {
this.head = node1.next
}else {
node1.prev.next = node1.next
}
if (index !== this.length - 1){
node1.next.prev = node1.prev
}
this.length--
return index
}
node1 = node1.next
index ++
}
return -1
}
LinkedList_twoWay.prototype.isEmpty = function() {
return this.head === null ? true : false
}
LinkedList_twoWay.prototype.size = function() {
return this.length
}
LinkedList_twoWay.prototype.toString = function() {
let node1 = this.head
let arr = []
while(node1 !== null) {
arr.push(node1.element)
node1 = node1.next
}
return arr.join(',')
}
LinkedList_twoWay.prototype.reverseToString = function() {
let node1 = this.tail
let arr = []
while(node1 !== null) {
arr.push(node1.element)
node1 = node1.prev
}
return arr.join(',')
}
}