數組不總是組織數據的最佳數據結構,因爲數組的長度是固定的,所以當數組已被數據填滿時,要再加入新的元素就會非常困難。在數組中,添加和刪除元素也很麻煩,因爲需要將數組中的其他元素向前或向後平移,以反映數組剛剛進行了添加和刪除操作。然而,JavaScript 的數組並不存在上述問題,因爲使用split() 方法不需要再訪問數組中的其他元素了。JavaScript中的數組的主要問題是,它們被實現成了對象,與其他語言相比,效率很低。如果你發現數組在實際使用時很慢,就可以考慮使用鏈表來替代它。除了對數據的隨機訪問,鏈表幾乎可以用在任何可以使用一維數組的情況中。如果需要隨機訪問,數組仍然是更好的選擇。
鏈表中插入節點的效率很高,刪除節點也很簡單。鏈表還有其他操作,但插入和刪除元素最能說明鏈表爲什麼如此有用。
鏈表包括兩個類。Node 類用來表示節點,LinkedList類提供了插入節點、刪除節點、顯示列表元素的方法,以及其他一些輔助方法。
<span style="white-space:pre"> </span>function Node(element) {
this.element = element;
this.next = null;
}
function LList() {
this.head = new Node("head");
this.find = find;
this.insert = insert;
this.remove = remove;
this.display = display;
this.findPrevious = findPrevious;
function find(elem) {
var curNode = this.head;
while(curNode.element !== elem&&curNode!==null) {
curNode = curNode.next;
}
return curNode;
}
function insert(newElem, item) {
var node = new Node(newElem),
current = this.find(item);
node.next = current.next;
current.next = node;
}
function findPrevious(elem) {
var curNode = this.head;
while((curNode.next!==null)&&(curNode.next.element !== elem)) {
curNode = curNode.next;
}
return curNode;
}
function remove(elem) {
var preNode = this.findPrevious(elem);
if(preNode.next!==null) {
preNode.next = preNode.next.next;
}
}
function display() {
var curNode = this.head;
while(curNode.next!==null) {
console.log(curNode.next.element);
curNode = curNode.next;
}
}
}
var cities = new LList();
cities.insert("Conway", "head");
cities.insert("Russellville", "Conway");
cities.insert("Carlisle", "Russellville");
cities.insert("Alma", "Carlisle");
cities.remove("Alma");