您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關怎么JavaScript中實現一個雙向鏈表,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
原理如下圖所示:
示例代碼:
/*雙向鏈表 * */ function Node(element) { this.element = element; this.next = null; this.previous = null;//雙向鏈表在這里需要增加一個previous屬性 } function LList() { this.head = new Node("head"); this.find = find; this.insert = insert; this.display = display; this.remove = remove; this.findLast = findLast; this.dispReverse = dispReverse;//將鏈表反轉 } function dispReverse() { var currNode = this.head; currNode = this.findLast(); var nodestr = ""; while (!(currNode.previous == null)) { nodestr += " "+currNode.element; currNode = currNode.previous; } console.log("將鏈表反轉后: "+nodestr); } function findLast() { var currNode = this.head; while (!(currNode.next == null)) { currNode = currNode.next; } return currNode; } function remove(item) { var currNode = this.find(item); if (!(currNode.next == null)) { currNode.previous.next = currNode.next; currNode.next.previous = currNode.previous; currNode.next = null; currNode.previous = null; } } // findPrevious is no longer needed /*function findPrevious(item) { var currNode = this.head; while (!(currNode.next == null) && (currNode.next.element != item)) { currNode = currNode.next; } return currNode; }*/ function display() { var currNode = this.head; var nodestr = ""; while (!(currNode.next == null)) { nodestr += " "+currNode.next.element; currNode = currNode.next; } console.log(nodestr); } function find(item) { var currNode = this.head; while (currNode.element != item) { currNode = currNode.next; } return currNode; } function insert(newElement, item) { var newNode = new Node(newElement); var current = this.find(item); newNode.next = current.next; newNode.previous = current;//雙向鏈表在這里需要設置新節點previous屬性 current.next = newNode; } var cities = new LList(); cities.insert("Conway", "head"); cities.insert("Russellville", "Conway"); cities.insert("Carlisle", "Russellville"); cities.insert("Alma", "Carlisle"); cities.display();//Conway Russellville Carlisle Alma cities.remove("Carlisle"); cities.display();//Conway Russellville Alma cities.dispReverse();// Alma Russellville Conway
這里使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun測試上述代碼,可得如下運行結果:
上述就是小編為大家分享的怎么JavaScript中實現一個雙向鏈表了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。