欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JS基于对象的链表实现与使用方法示例

程序员文章站 2023-11-12 18:55:04
本文实例讲述了js基于对象的链表实现与使用方法。分享给大家供大家参考,具体如下: 链表是一种在物理内存上不连续的数据结构。原理如下图所示: 示例代码: /...

本文实例讲述了js基于对象的链表实现与使用方法。分享给大家供大家参考,具体如下:

链表是一种在物理内存上不连续的数据结构。原理如下图所示:

JS基于对象的链表实现与使用方法示例

示例代码:

/*js实现一个基于对象的链表*/
function node(element){
  this.element = element;//节点存储的元素
  this.next = null;//节点指向的下一个节点,这里先设置为空
}
function llist(){
  this.head = new node("head");//生成一个头节点
  this.find = find;//在链表中找到某个节点
  this.insert = insert;//在链表中某个元素后面插入某个节点元素
  this.display = display;//在将链表中的节点元素显示出来
  this.findprevious = findprevious;//找到某个节点的上一个节点
  this.remove = remove;//删除某个节点
}
function remove(item) {
  var prevnode = this.findprevious(item);
  if (!(prevnode.next == null)) {
    prevnode.next = prevnode.next.next;
  }
}
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;
  current.next = newnode;
}
/*测试例子*/
var num = new llist();
num.insert("a1","head");
num.insert("b1","a1");
num.insert("c1","b1");
num.display();// a1 b1 c1
num.remove("b1");
num.display();// a1 c1

这里使用在线html/css/javascript代码运行工具http://tools.jb51.net/code/htmljsrun测试上述代码,可得如下运行结果:

JS基于对象的链表实现与使用方法示例

更多关于javascript相关内容感兴趣的读者可查看本站专题:《javascript数据结构与算法技巧总结》、《javascript数学运算用法总结》、《javascript排序算法总结》、《javascript遍历算法与技巧总结》、《javascript查找算法技巧总结》及《javascript错误与调试技巧总结

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