亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

使用JavaScript實現(xiàn)鏈表的數(shù)據結構的代碼

 更新時間:2017年08月02日 09:37:09   投稿:mrr  
鏈表(Linked list)是一種常見的基礎數(shù)據結構,是一種線性表,但是并不會按線性的順序存儲數(shù)據,而是在每一個節(jié)點里存到下一個節(jié)點的指針(Pointer) 。下面我們用 JavaScript 代碼對鏈表的數(shù)據結構進行實現(xiàn)

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

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

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

/**
 * Node 類用來表示節(jié)點
 * element 用來保存節(jié)點上的數(shù)據
 * next 用來保存指向下一個節(jié)點的鏈接
 */
function Node(element) {
 this.element = element;
 this.next = null;
}
LList類提供對鏈表操作的方法
/**
 * LList 類提供了對鏈表進行操作的方法
 * 鏈表只有一個屬性,
 * 使用一個 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] } } }

上面就是用JavaScript對簡單鏈表的數(shù)據結構的簡單實現(xiàn):smile:

總結

以上所述是小編給大家介紹的使用JavaScript實現(xiàn)鏈表的數(shù)據結構的代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!

相關文章

最新評論