用Javascript實現連結串列
阿新 • • 發佈:2018-11-07
github主頁:https://github.com/A15162252289
什麼是連結串列
連結串列儲存有序的元素集合,但不同於陣列,連結串列中的元素在記憶體中不是連續放置的。每個元素由一個儲存元素本身的節點和指向下一個元素的引用組成。
下圖為單向連結串列的示意圖
相對於傳統陣列連結串列的好處在於,新增和刪除元素的時候不需要移動其他元素。然而,連結串列需要使用指標,因此實現連結串列時應該額外注意。陣列的另一個細節是可以直接訪問任何位置的元素,而想要訪問連結串列中間的一個元素,需要從起點(表頭)開始迭代列表直到找到所需元素。
如何實現單向連結串列
function LinkedList () {
let Node = function (element) {
this.element = element;
this.next = null;
}; //定義連結串列中單個節點
let length = 0; //定義連結串列長度
let head = null; //定義連結串列第一項
this.append = function (element) {
let node = new Node(element);
let curNode;
if (head == null) {
head = node;
} else {
curNode = head;
while (curNode.next) {
curNode = curNode.next;
}
curNode.next = node;
}
length++;
}; //向連結串列末尾新增一項
this.removeAt = function (position) {
//檢查越界值
if (position > -1 && position < length) {
let curNode = head;
let preNode;
let index = 0;
if (position === 0) {
head = curNode.next;
} else {
while (index++ < position) {
preNode = curNode;
curNode = curNode.next;
}
preNode.next = curNode.next;
}
length--;
return curNode.element;
}
}; //刪除特定位置的某項
this.insert = function (position, element) {
let node = new Node(element);
let curNode = head;
let preNode;
let index = 0;
if (position >= 0 && position <= length) {
if (position === 0) {
head = node;
node.next = curNode;
} else {
while (index++ < position) {
preNode = curNode;
curNode = curNode.next;
}
preNode.next = node;
node.next = curNode;
}
length++;
return true;
} else {
return false;
}
}; //將元素新增到指定位置
//其他方法
}
這裡實現了最重要的幾種方法,其他的不做贅述;