function LinkedList() {
// 内部类
function Node(data) {
this.data = data
this.next = null
}
// 属性
this.head = null
this.length = 0
// 列表尾部添加
LinkedList.prototype.append = function(element) {
let newNode = new Node(element)
if(this.length === 0) {
this.head = newNode
} else {
let current = this.head
while(current.next) {
current = current.next
}
current.next = newNode
}
this.length += 1
}
// 任意位置添加
LinkedList.prototype.insert = function(position, element) {
if(position < 0 || position > this.length) {
return false
}
let newNode = new Node(element)
if(position === 0) {
newNode.next = this.head
this.head = newNode
} else {
let index = 0
let current = this.head
while(index++ < position - 1){
current = current.next
}
newNode.next = current.next
current.next = newNode
}
this.length += 1
}
// 获取对应位置的元素
LinkedList.prototype.get = function(position) {
if(position < 0 || position > this.length) {
return false
}
let index = 0
let current = this.head
while(index++ < position){
current = current.next
}
return current.data
}
// 返回元素在列表中的索引,如果没有则返回-1
LinkedList.prototype.indexOf = function(element) {
let current = this.head
let index = 0
while(current.next) {
if(element === current.data) {
return index
} else {
index += 1
current = current.next
}
}
if(current.data === element) {
return this.length - 1
}
return -1
}
// 修改某元素
LinkedList.prototype.update = function(position, element) {
if(position < 0 || position >= this.length) {
return false
}
let index = 0
let current = this.head
while(index++ < position){
current = current.next
}
current.data = element
}
// 从特定位置移除一项
LinkedList.prototype.removeAt = function(position) {
if(position < 0 || position >= this.length) {
return null
}
let index = 0
let current = this.head
if(position === 0) {
this.head = current.next
} else {
let previous = null
while(index++ < position){
previous = current
current = current.next
}
previous.next = current.next
}
this.length -= 1
return current.data
}
// 从列表中移除一项
LinkedList.prototype.remove = function(element) {
let position = this.indexOf(element)
if(position < 0) return undefined
return this.removeAt(position)
}
LinkedList.prototype.isEmpty = function() {
return this.head === null
}
LinkedList.prototype.size = function() {
return this.length
}
LinkedList.prototype.toString = function() {
let current = this.head
let listString = ''
while(current) {
listString += current.data + ' '
current = current.next
}
return listString
}
}
let linkList = new LinkedList()
linkList.append('a')
linkList.append('b')
linkList.append('c')
linkList.append('d')
console.log(linkList.toString());
linkList.insert(2,'1')
console.log(linkList.toString());
console.log(linkList.get(0));
console.log(linkList.indexOf('x'));
linkList.update(5,'b');
console.log(linkList.toString());
console.log(linkList.removeAt(3));
console.log(linkList.toString());
console.log(linkList.remove('m'));
console.log(linkList.toString());
javascript链表实现
最新推荐文章于 2024-01-12 07:15:00 发布