鏈表(Linked list)是一種常見的基礎數據結構,是一種線性表,但是並不會按線性的順序存儲數據,而是在每一個節點裡存到下一個節點的指針(Pointer) — 維基百科
上面是維基百科對 鏈表 的解讀。下面我們用 JavaScript 代碼對鏈表的數據結構進行實現
實現Node類表示節點
/**
* Node 類用來表示節點
* element 用來保存節點上的數據
* next 用來保存指向下一個節點的鏈接
*/
function Node(element) {
this.element = element;
this.next = null;
}
LList類提供對鏈表操作的方法
/**
* LList 類提供了對鏈表進行操作的方法
* 鏈表只有一個屬性,
* 使用一個 Node 對象來保存該鏈表的頭節點。
*/
class LList {
constructor() {
this.head = new Node('head');
}
// 查找節點
find(item) {
let currNode = this.head;
while(currNode.element !== item) {
currNode = currNode.next;
}
return currNode;
}
// 查找前一個節點
findPre(item) {
if(item === 'head') throw new Error('now is head!');
let currNode = this.head;
while (currNode.next && currNode.next.element !== item) {
currNode = currNode.next;
}
return currNode;
}
// 插入新節點
insert(newElement, item) {
let newNode = new Node(newElement);
let currNode = this.find(item);
newNode.next = currNode.next;
currNode.next = newNode;
}
// 刪除一個節點
remove(item) {
let preNode = this.findPre(item);
if(preNode.next !== null) {
preNode.next = preNode.next.next;
}
}
// 顯示鏈表中的元素
display() {
let currNode = this.head;
while(currNode.next !== null) {
console.log(currNode.next.element);
currNode = currNode.next;
}
}
}
測試代碼
const list = new LList();
// LList { head: Node { element: 'head', next: null } }
list.insert('0', 'head');
list.insert('1', '0');
list.insert('2', '1');
list.insert('3', '2');
list.remove('1');
console.log(list);
// LList { head: Node { element: 'head', next: Node { element: '0', next: [Object] } } }
console.log(list.display()); // 0 2 3
console.log(list.findPre('1'));
// Node { element: '0', next: Node { element: '1', next: Node { element: '2', next: [Object] } } }
上面就是用JavaScript對簡單鏈表的數據結構的簡單實現:smile:
總結
以上所述是小編給大家介紹的使用JavaScript實現鏈表的數據結構的代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對網站的支持!