您的位置:首页 > Web前端 > JavaScript

JS双向链表实现与使用方法示例(增加一个previous属性实现)

2019-05-01 18:01 901 查看

本文实例讲述了JS双向链表实现与使用方法。分享给大家供大家参考,具体如下:

前面一篇讲述了《JS基于对象的链表实现与使用方法》,这里的双向链表通过增加一个previous属性实现。

单链表中若需要查找某一个元素时,必须从第一个元素开始进行查找,而双向链表除开头节点和最后一个节点外每个节点中储存有两个指针,这连个指针分别指向前一个节点的地址和后一个节点的地址,这样无论通过那个节点都能够寻找到其他的节点。

原理如下图所示:

示例代码:

/*双向链表
* */
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相关内容感兴趣的读者可查看本站专题:《JavaScript数据结构与算法技巧总结》、《JavaScript数学运算用法总结》、《JavaScript排序算法总结》、《JavaScript遍历算法与技巧总结》、《JavaScript查找算法技巧总结》及《JavaScript错误与调试技巧总结

希望本文所述对大家JavaScript程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐