国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

如何用JavaScript實現功能齊全的單鏈表詳解

2024-05-06 15:42:34
字體:
來源:轉載
供稿:網友

前言

前端也要搞好數據結構哦!

用JavaScript實現了個單鏈表,通過LinkedList構造函數可實例化一個單鏈表數據結構的對象,所有的方法放到LinkedList構造函數的原型對象上,寫了暫時能想到的所有方法

GitHub源碼地址,下載可運行

實現

通過LinkedList的類創建鏈表實例,鏈表下有添加,查找,刪除,顯示節點等方法 鏈表初始默認有一個"_head"頭部節點,使用時隱藏 按元素/索引 添加、刪除,未找到時返回錯誤,查找未找到時返回null或-1 let obj = new LinkedList()

方法介紹

查找

obj.find(item)通過item元素內容查找到該元素 obj.findIndex(index)通過index索引查找到該元素 obj.findIndexOf(item)通過item元素內容查找到該元素索引 obj.findPrev(item)通過item元素查找上一個節點元素

添加

obj.insert(item,newElement)在item元素后插入新元素 obj.push(item)在鏈表末尾插入item元素 obj.insertIndex(index,newElement)在index索引處插入新元素

刪除

obj.remove(item)刪除item元素 obj.removeIndex(index)刪除index索引處節點

其他

obj.size()返回該鏈表的長度 obj.display()數組形式返回該鏈表,便于觀察,測試 obj.reversal()鏈表順序反轉(遞歸)

方法代碼

鏈表類LinkedList

 function LinkedList (...rest) { this._head = new Node('_head') // 鏈表頭節點 // 如果new時有傳進值,則添加到實例中 if (rest.length) { this.insert(rest[0], '_head') for (let i = 1; i < rest.length; i++) { this.insert(rest[i], rest[i - 1]) } } } LinkedList.prototype.find = find LinkedList.prototype.findPrev = findPrev LinkedList.prototype.findIndex = findIndex LinkedList.prototype.findIndexOf = findIndexOf LinkedList.prototype.push = push LinkedList.prototype.insert = insert LinkedList.prototype.insertIndex = insertIndex LinkedList.prototype.remove = remove LinkedList.prototype.removeIndex = removeIndex LinkedList.prototype.size = size LinkedList.prototype.display = display LinkedList.prototype.reversal = reversal

創建新節點類Node

 function Node (element) { this.element = element this.next = null }

obj.find(item)

// 查找函數,在鏈表中查找item的位置,并把它返回,未找到返回-1 function find (item) { let currNode = this._head while (currNode !== null && currNode.element !== item) { currNode = currNode.next } if (currNode !== null) { return currNode } else { return null } }

obj.findIndex(index)

// 通過元素的索引返回該元素 function findIndex (index) { let currNode = this._head let tmpIndex = 0 while (currNode !== null) { // 找到該index位置,返回當前節點,出去頭結點 if (tmpIndex === index + 1) { return currNode } tmpIndex += 1 currNode = currNode.next } return null }            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 自治县| 龙口市| 钟山县| 平陆县| 仁布县| 柳林县| 韶关市| 清水河县| 兴业县| 南投市| 缙云县| 公安县| 靖远县| 东源县| 平罗县| 垫江县| 牙克石市| 柳江县| 江源县| 搜索| 双峰县| 崇义县| 达拉特旗| 东乡县| 张家界市| 湖南省| 安徽省| 武安市| 岐山县| 昭平县| 宁城县| 保山市| 射阳县| 邛崃市| 梁山县| 北川| 兰考县| 淳安县| 阳城县| 尚志市| 广饶县|