解题思路
首先是 get:
我们先思考索引无效的情况,当索引:小于 0,大于等于链表长度,我们认为是无效索引,因为这些 index 上没有节点。
因此在查找之前,我们处理小于零的情况,如果小于0,直接返回 -1,另外对于没有 head 的情况,我们也直接 return -1。
然后,我们声明一个变量 cur,先指向 head, 用一个计数器 count 来找 index,并且不断移动 cur,如果 index 超出范围, return -1,否则当 count === index,我们就找到了要找的节点
addAtHead: 我们创造一个节点,然后让他指向 this.head.next,随后将 this.head 指向创造的新节点
addAtTail:我们注意要处理没有头节点的情况,然后其他操作和查找元素相同,我们要找的是 tail 节点,然后让 tail.next 指向我们要追加的新节点
addAtIndex:
注意这里题目要求,小于零的要放到头部,所以我们先确定的一点是,如果给我们的 index < 0,我们在头部追加节点。
然后查找追加位置,和上面一样。
deleteAtIndex:
和上面的查找过程一样的~
var MyLinkedList = function () {
this.head = null
}
/**
* @param {number} index
* @return {number}
*/
MyLinkedList.prototype.get = function (index) {
if (index < 0) {
return -1
}
let count = 0
let cur = this.head
if (!cur) return -1
while (index !== count) {
cur = cur.next
count++
if (!cur) return -1
}
if (index !== count) return -1
return cur.val
}
/**
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtHead = function (val) {
const newNode = { val, next: this.head }
this.head = newNode
}
/**
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtTail = function (val) {
let cur = this.head
const newNode = { val, next: null }
if (!cur) {
this.head = newNode
return
}
while (cur.next) {
cur = cur.next
}
cur.next = newNode
}
/**
* @param {number} index
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtIndex = function (index, val) {
const newNode = { val, next: null }
if (index <= 0) {
newNode.next = this.head
this.head = newNode
}
let count = 1
let cur = this.head
while (index !== count) {
count++
if (!cur) return
cur = cur.next
}
if (cur) {
newNode.next = cur.next
cur.next = newNode
}
}
/**
* @param {number} index
* @return {void}
*/
MyLinkedList.prototype.deleteAtIndex = function (index) {
if (index < 0) {
return
}
if (index === 0) {
this.head = this.head.next
return
}
let cur = this.head
let count = 1
while (index !== count) {
count++
cur = cur.next
if (!cur) return
}
cur.next = cur.next && cur.next.next
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* var obj = new MyLinkedList()
* var param_1 = obj.get(index)
* obj.addAtHead(val)
* obj.addAtTail(val)
* obj.addAtIndex(index,val)
* obj.deleteAtIndex(index)
*/