设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val 和 next。val 是当前节点的值,next 是指向下一个节点的指针/引用。如果要使用双向链表,则还需要一个属性 prev 以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。
var MyLinkedList = function () {
this.len = 0
this.dummy = new ListNode(-1, null)
}
function ListNode(val, next) {
this.val = val
this.next = next
}
/**
* @param {number} index
* @return {number}
*/
MyLinkedList.prototype.get = function (index) {
if (index < this.len && index >= 0) {
let cur = this.dummy.next
while (index-- > 0) {
cur = cur.next
}
return cur.val
}
return -1
}
/**
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtHead = function (val) {
this.addAtIndex(0, val)
}
/**
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtTail = function (val) {
this.addAtIndex(this.len, val)
}
/**
* @param {number} index
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtIndex = function (index, val) {
if (index <= this.len) {
let pre = this.dummy
let count = Math.max(0, index)
while (count-- > 0) {
pre = pre.next
}
if (index === this.len) {
pre.next = new ListNode(val, null)
} else {
pre.next = new ListNode(val, pre.next)
}
this.len++
}
}
/**
* @param {number} index
* @return {void}
*/
MyLinkedList.prototype.deleteAtIndex = function (index) {
if (index < this.len && index >= 0) {
let pre = this.dummy
while (index-- > 0) {
pre = pre.next
}
if (pre.next) {
pre.next = pre.next.next
} else {
pre.next = null
}
this.len--
}
}