設計鏈表
一、LeetCode題解
瞧一瞧~
- 博健的LeetCode題解:Gitbook版本傳送門
- 博健的LeetCode題解:CSDN傳送門
- 前端進階筆記:Gitbook傳送門
二、算法題
題目
設計鏈表的實現。您可以選擇使用單鏈表或雙鏈表。單鏈表中的節點應該具有兩個屬性:val 和 next。val 是當前節點的值,next 是指向下一個節點的指針/引用。如果要使用雙向鏈表,則還需要一個屬性 prev 以指示鏈表中的上一個節點。假設鏈表中的所有節點都是 0-index 的。
在鏈表類中實現這些功能:
get(index):獲取鏈表中第 index 個節點的值。如果索引無效,則返回-1。
addAtHead(val):在鏈表的第一個元素之前添加一個值爲 val 的節點。插入後,新節點將成爲鏈表的第一個節點。
addAtTail(val):將值爲 val 的節點追加到鏈表的最後一個元素。
addAtIndex(index,val):在鏈表中的第 index 個節點之前添加值爲 val 的節點。如果 index 等於鏈表的長度,則該節點將附加到鏈表的末尾。如果 index 大於鏈表長度,則不會插入節點。如果index小於0,則在頭部插入節點。
deleteAtIndex(index):如果索引 index 有效,則刪除鏈表中的第 index 個節點。
示例:
MyLinkedList linkedList = new MyLinkedList();
linkedList.addAtHead(1);
linkedList.addAtTail(3);
linkedList.addAtIndex(1,2); //鏈表變爲1-> 2-> 3
linkedList.get(1); //返回2
linkedList.deleteAtIndex(1); //現在鏈表是1-> 3
linkedList.get(1); //返回3
代碼
var Node = function(ele){
this.ele = ele
this.next = null
}
/**
* Initialize your data structure here.
*/
var MyLinkedList = function() {
this.head = new Node('head')
};
/**
* 查詢 index 位下節點的值
* @param {number} index
* @return {number}
*/
MyLinkedList.prototype.get = function(index) {
var i = 0
var current = this.head
while(current.next){
if(i == index){
return current.next.ele
}
i++
current = current.next
}
return -1
};
/**
* 插入到鏈表首位
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtHead = function(val) {
var current = this.head
var node = new Node(val)
node.next = current.next
current.next = node
};
/**
* 插入到鏈表首末位
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtTail = function(val) {
var current = this.head
while(current.next){
current = current.next
}
var node = new Node(val)
current.next = node
};
/**
* 在 index 位置插入值爲 val 的節點
* @param {number} index
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtIndex = function(index, val) {
if(index < 0){
this.addAtHead(val)
return;
}
var current = this.head
var i = 0
while(current.next){
if(i == index){
var node = new Node(val)
node.next = current.next
current.next = node
return;
}
i++
current = current.next
}
this.addAtTail(val)
return;
};
/**
* Delete the index-th node in the linked list, if the index is valid.
* @param {number} index
* @return {void}
*/
MyLinkedList.prototype.deleteAtIndex = function(index) {
if(index < 0) return;
var i = 0
var current = this.head
while(current.next){
if(i == index){
current.next = current.next.next
return;
}
i++
current = current.next
}
};