溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么使用JavaScript實現(xiàn)鏈表的數(shù)據(jù)結(jié)構(gòu)的代碼

發(fā)布時間:2021-04-13 14:17:28 來源:億速云 閱讀:125 作者:小新 欄目:web開發(fā)

這篇文章主要介紹了怎么使用JavaScript實現(xiàn)鏈表的數(shù)據(jù)結(jié)構(gòu)的代碼,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

鏈表(Linked list)是一種常見的基礎(chǔ)數(shù)據(jù)結(jié)構(gòu),是一種線性表,但是并不會按線性的順序存儲數(shù)據(jù),而是在每一個節(jié)點里存到下一個節(jié)點的指針(Pointer)   — 維基百科

上面是維基百科對 鏈表 的解讀。下面我們用 JavaScript 代碼對鏈表的數(shù)據(jù)結(jié)構(gòu)進(jìn)行實現(xiàn)

實現(xiàn)Node類表示節(jié)點

/**
 * Node 類用來表示節(jié)點
 * element 用來保存節(jié)點上的數(shù)據(jù)
 * next 用來保存指向下一個節(jié)點的鏈接
 */
function Node(element) {
 this.element = element;
 this.next = null;
}
LList類提供對鏈表操作的方法
/**
 * LList 類提供了對鏈表進(jìn)行操作的方法
 * 鏈表只有一個屬性,
 * 使用一個 Node 對象來保存該鏈表的頭節(jié)點。
 */
class LList {
 constructor() {
  this.head = new Node('head');
 }
 // 查找節(jié)點
 find(item) {
  let currNode = this.head;
  while(currNode.element !== item) {
   currNode = currNode.next;
  }
  return currNode;
 }
 // 查找前一個節(jié)點
 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;
 }
 // 插入新節(jié)點
 insert(newElement, item) {
  let newNode = new Node(newElement);
  let currNode = this.find(item);
  newNode.next = currNode.next;
  currNode.next = newNode;
 }
 // 刪除一個節(jié)點
 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] } } }

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“怎么使用JavaScript實現(xiàn)鏈表的數(shù)據(jù)結(jié)構(gòu)的代碼”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI