设计链表
- LeetCode题目链接
- 卡尔老师代码随想录讲解
- 关键点: 这道题目包含了设计链表的基础API,包括得到链表中相对应索引的值、在链表头部添加节点、在链表尾部添加节点、在给定索引值的元素前面添加节点、删除给定索引的节点。在完善这些API时要特别注意头部节点、尾部节点、空链表、单节点链表的特殊情况,需要我们重点考虑。 在题目要求之外我们设计了一个 getNode 用于快速获取相应索引的节点方便被设计的 API 调用。
- 代码:
function LinkNode (val,next) {
this.val = (val === undefined ? null : val )
this.next = (next === undefined ? null : next)
}
var MyLinkedList = function() {
this._head = null
this._tail = null
this._size = 0
};
MyLinkedList.prototype.getNode = function (index) {
if (index < 0 || index >= this._size) return null
let cur = new LinkNode (null,this._head)
while (index-- >=0) {
cur = cur.next
}
return cur
}
MyLinkedList.prototype.get = function(index) {
if (index < 0 || index >= this._size) {
return -1
} else {
return this.getNode(index).val
}
};
MyLinkedList.prototype.addAtHead = function(val) {
let newNode = new LinkNode (val,null)
if (this._size == 0) {
this._head = newNode
this._tail = newNode
this._size ++
return
}
newNode.next = this._head
this._head = newNode
this._size++
};
MyLinkedList.prototype.addAtTail = function(val) {
let newNode = new LinkNode (val,null)
if (this._tail ) {
this._tail.next = newNode
this._tail = newNode
} else {
this._tail = newNode
this._head = newNode
}
this._size++
};
MyLinkedList.prototype.addAtIndex = function(index, val) {
if(index <= 0) {
this.addAtHead(val)
} else if (index == this._size) {
this.addAtTail(val)
} else if (index < this._size) {
let cur = this.getNode(index-1)
let newNode = new LinkNode (val,null)
newNode.next = cur.next
cur.next = newNode
this._size++
}
}
MyLinkedList.prototype.deleteAtIndex = function(index) {
if(index >=0 && index < this._size) {
if (this._size > 1) {
if(index == 0 ){
this._head = this._head.next
} else {
let cur = this.getNode(index-1)
if(index == this._size-1) {
cur.next = null
this._tail =cur
}else {
cur.next = cur.next.next
}
}
this._size--
} else {
this._head = null
this._tail = null
this._size = 0
}
}
};
- 注意:
- 在添加头部和尾部节点时考虑空链表的特殊情况
- 在删除给定索引值的节点时,考虑空链表和单节点情况,考虑删除的节点是头元素和尾元素的情况
- 时间复杂度分析:
主要考察设计链表内容,不进行算法分析