数据结构与算法——链表
在这里插入代码片
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
function LinkedList() {
function Node(element) {
this.element = element
this.next = null
}
this.length = 0
this.head = null
LinkedList.prototype.append = function (element) {
var newNode = new Node(element)
if (this.head === null) {
this.head = newNode
} else {
var current = this.head
while (current.next) {
current = current.next
}
current.next = newNode
}
this.length++
}
LinkedList.prototype.toString = function () {
var current = this.head
var listString = ""
while (current) {
listString += "," + current.element
current = current.next
}
return listString.slice(1)
}
LinkedList.prototype.insert = function (position, element) {
if (position < 0 || position > this.length) return false
var newNode = new Node(element)
var current = this.head
var previous = null
index = 0
if (position == 0) {
newNode.next = current
this.head = newNode
} else {
while (index++ < position) {
previous = current
current = current.next
}
newNode.next = current
previous.next = newNode
}
this.length++
return true
}
LinkedList.prototype.removeAt = function (position) {
if (position < 0 || position >= this.length) return null
var current = this.head
var previous = null
var index = 0
if (position === 0) {
this.head = current.next
} else {
while (index++ < position) {
previous = current
current = current.next
}
previous.next = current.next
}
this.length--
return current.element
}
LinkedList.prototype.indexOf = function (element) {
var current = this.head
index = 0
while (current) {
if (current.element === element) {
return index
}
index++
current = current.next
}
return -1
}
LinkedList.prototype.remove = function (element) {
var index = this.indexOf(element)
return this.removeAt(index)
}
LinkedList.prototype.isEmpty = function () {
return this.length == 0
}
LinkedList.prototype.size = function () {
return this.length
}
LinkedList.prototype.getFirst = function () {
return this.head.element
}
}
var list = new LinkedList()
list.append(15)
list.append(10)
list.append(20)
alert(list)
list.insert(0, 100)
list.insert(4, 200)
list.insert(2, 300)
alert(list)
list.removeAt(0)
list.removeAt(1)
list.removeAt(3)
alert(list)
list.remove(15)
alert(list)
alert(list.isEmpty())
alert(list.size())
alert(list.getFirst())
document.write('\u66f4\u591a\u6559\u7a0b\u8bf7\u8bbf\u95ee\u0020\u0069\u0074\u006a\u0063\u0038\u002e\u0063\u006f\u006d');
</script>
</body>
</html>
|