链表包含两个类,一个是 Node 类用来表示节点,另一个事 LinkedList 类提供插入节点、删除节点等一些操作。

Node类

Node类包含连个属性: element 用来保存节点上的数据,next 用来保存指向下一个节点的链接,具体实现如下:

  1. //节点
  2. function Node(element) {
  3. this.element = element; //当前节点的元素
  4. this.next = null; //下一个节点链接
  5. }

同理,双向链表,只是多一个指向而已。

  1. //节点类
  2. function Node(element) {
  3. this.element = element; //当前节点的元素
  4. this.next = null; //下一个节点链接
  5. this.previous = null; //上一个节点链接
  6. }

LinkedList类

list只有一个属性,就是头结点;find、insert、remove、findPrev、display是自己实现的功能函数

  1. //链表类
  2. function LList () {
  3. this.head = new Node( 'head' ); //头节点
  4. this.find = find; //查找节点
  5. this.insert = insert; //插入节点
  6. this.remove = remove; //删除节点
  7. this.findPrev = findPrev; //查找前一个节点
  8. this.display = display; //显示链表
  9. }