链表以及数组的缺点:
链表的优势:
链表的结构:
封装一个链表类:
链表中保存两个属性,一个是链表的长度,一个是链表中第一个节点。
链表的常见操作:
append方法:
toString方法:
insert方法:
……
单向链表:
双向链表:
双向链表的结构:
双向链表的常见操作:
var MyLinkedList = function () {
this.head = null
this.length = 0
};
var Node = function (element, next) {
this.element = element
this.next = null
}
/**
* @param {number} index
* @return {number}
*/
MyLinkedList.prototype.get = function (index) {
if (index < 0 || index >= this.length) return -1
var cur = this.head
var temp = 0
while (temp++ < index) {
cur = cur.next
}
return cur.element
};
/**
* @param {number} val
* @return {void}
*/
//添加到第一个节点
MyLinkedList.prototype.addAtHead = function (val) {
var node = new Node(val)
var cur = this.head
node.next = cur
this.head = node
this.length++
return
};
/**
* @param {number} val
* @return {void}
*/
//添加到最后一个节点
MyLinkedList.prototype.addAtTail = function (val) {
var node = new Node(val)
var cur = this.head
var temp = 0
if (this.length == 0) {
this.addAtHead(val)
return
}
while (temp++ < this.length - 1) {
cur = cur.next
}
node.next = null
cur.next = node
this.length++
return
};
/**
* @param {number} index
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtIndex = function (index, val) {
var node = new Node(val)
if (this.length == 0) {
if (index <= 0) {
this.addAtHead(val)
return
} else {
return
}
}
else {
if (index == this.length) {
this.addAtTail(val)
return
}
else if (index > this.length) {
return
}
else if (index <= 0) {
// this.deleteAtIndex(0)
this.addAtHead(val)
return
}
else {
temp = 0
var cur = this.head
var previous = null
while (temp++ < index) {
previous = cur
cur = cur.next
}
previous.next = node
node.next = cur
this.length++
return
}
}
};