# JS数据结构学习：链表

william

## 链表的创建

``````function LinkedList() {
let Node = function (element) {
this.element = element
this.next = null
}
let length = 0
this.append = function (element) {
}
this.insert = function (position, element) {
}
this.removeAt = function (position) {
}
this.remove = function (element) {
}
this.indexOf = function (element) {
}
this.isEmpty = function () {
}
this.size = function () {
}
}
this.toString = function () {
}
this.print = function () {
}
}``````

### append(向链表尾部追加元素)

``````this.append = function (element) {
let node = new Node(element), current
} else {
current = node
while (current.next) { // 循环链表，直到最后一项
current = current.next
}
current.next = node // 找到最后一项，将新增元素连接
}
length++
}``````

### removeAt(移除元素)

``````this.removeAt = function (position) {
if (position > -1 && position < length) { // 判断边界
let previous, index = 0, current = head
if (position === 0) { // 移除第一项
} else {
while (index++ < position) {
previous = current
current = current.next
}
previous.next = current.next
}
length--
return current.element
} else {
return null
}
}``````

### insert(任意位置插入)

``````this.insert = function (position, element) {
if (position > -1 && position <= length) {
let node = new Node(element),previous, index = 0, current = head
if (position === 0) {
node.next = current
} else {
while (index++ < position) {
previous = current
current = current.next
}
previous.next = node
node.next = current
}
length++
return true
} else {
return false
}
}``````

### toString

``````this.toString = function () {
let current = head, string = ''
while (current) {
string += current.element + (current.next ? 'n' : '')
current = current.next
}
return string
}``````

### indexOf

indexOf方法返回对应元素的位置，存在就返回对应的索引，不存在返回-1，来看具体的实现：

``````this.indexOf = function (element) {
let current = head, index = 0
while (current) {
if (current.element === element) {
return index
}
index++
current = current.next
}
return -1
}``````

``````this.remove = function (element) { // 移除指定元素
let index = this.indexOf(element)
return this.removeAt(index)
}
this.isEmpty = function () { // 判断链表是否为空
return length === 0
}
this.size = function () { // 获取链表长度
return length
}
this.getHead = function () { // 获取链表头
}``````

love and share

2.6k 声望
824 粉丝
0 条评论