JavaScript 雙向鏈表操作實(shí)例分析【創(chuàng)建、增加、查找、刪除等】
本文實(shí)例講述了JavaScript 雙向鏈表操作。分享給大家供大家參考,具體如下:
一個(gè) 雙向鏈表(doubly linked list) 是由一組稱為節(jié)點(diǎn)的順序鏈接記錄組成的鏈接數(shù)據(jù)結(jié)構(gòu)。每個(gè)節(jié)點(diǎn)包含兩個(gè)字段,稱為鏈接,它們是對(duì)節(jié)點(diǎn)序列中上一個(gè)節(jié)點(diǎn)和下一個(gè)節(jié)點(diǎn)的引用
開始節(jié)點(diǎn)和結(jié)束節(jié)點(diǎn)的上一個(gè)鏈接和下一個(gè)鏈接分別指向某種終止節(jié)點(diǎn),通常是前哨節(jié)點(diǎn)或null,以方便遍歷列表。如果只有一個(gè)前哨節(jié)點(diǎn),則列表通過前哨節(jié)點(diǎn)循環(huán)鏈接。它可以被概念化為兩個(gè)由相同數(shù)據(jù)項(xiàng)組成的單鏈表,但順序相反。
class DNode { constructor(val) { this.val = val; this.prev = null; this.next = null; }}增加節(jié)點(diǎn)
function add(el) { var currNode = this.head; while (currNode.next != null) { currNode = currNode.next; } var newNode = new DNode(el); newNode.next = currNode.next; currNode.next = newNode;}查找
function find(el) { var currNode = this.head; while (currNode && currNode.el != el) { currNode = currNode.next; } return currNode;}插入
function (newEl, oldEl) { var newNode = new DNode(newEl); var currNode = this.find(oldEl); if (currNode) { newNode.next = currNode.next; newNode.prev = currNode; currNode.next = newNode; } else { throw new Error(’未找到指定要插入節(jié)點(diǎn)位置對(duì)應(yīng)的值!’) }}展示
// 順序function () { var currNode = this.head.next; while (currNode) { console.log(currNode.el); currNode = currNode.next; }}// 逆序function () { var currNode = this.head; currNode = this.findLast(); while (currNode.prev != null) { console(currNode.el); currNode = currNode.prev; }}刪除
function (el) { var currNode = this.find(el); if (currNode && currNode.next != null) { currNode.prev.next = currNode.next; currNode.next.prev = currNode.prev; currNode.next = null; currNode.previous = null; } else { throw new Error(’找不到要?jiǎng)h除對(duì)應(yīng)的節(jié)點(diǎn)’); }}
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運(yùn)行工具:http://tools.jb51.net/code/HtmlJsRun測(cè)試上述代碼運(yùn)行效果。
更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript數(shù)組操作技巧總結(jié)》、《JavaScript排序算法總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》、《JavaScript查找算法技巧總結(jié)》及《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》
希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。
相關(guān)文章:
1. Python如何批量生成和調(diào)用變量2. ASP.NET MVC實(shí)現(xiàn)橫向展示購(gòu)物車3. ASP.Net Core對(duì)USB攝像頭進(jìn)行截圖4. .net如何優(yōu)雅的使用EFCore實(shí)例詳解5. ASP.Net Core(C#)創(chuàng)建Web站點(diǎn)的實(shí)現(xiàn)6. python 爬取京東指定商品評(píng)論并進(jìn)行情感分析7. python基礎(chǔ)之匿名函數(shù)詳解8. Python獲取B站粉絲數(shù)的示例代碼9. ajax動(dòng)態(tài)加載json數(shù)據(jù)并詳細(xì)解析10. 通過CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動(dòng)畫特效
