双向链表

来源:互联网 发布:悍将传世源码 编辑:程序博客网 时间:2024/05/29 19:34

一、概述

  • 单链表虽然从头结点向尾结点遍历很简单,但反过来,从后往前遍历就麻烦了
  • 因此我们考虑通过给node结点增加一个属性,指向前驱,则从后往前遍历变得简单
  • 在删除节点时,无需查找前驱元素,效率会有所提高

这里写图片描述

二、对象的封装

  • 单链表中写的较详细,这儿直接贴代码,有疑问可以看看单链表那篇
  • 插入和删除建议自己动手一边画图一遍写代码

这里写图片描述

这里写图片描述

function Node(ele){    this.element = ele;    this.next = null;    this.pre = null;}function LinkedList(){    this.head = new Node("head");    this.find = find;               //遍历链表,查找给定的元素    this.insert = insert;           //插入节点    this.remove = remove;           //删除节点    this.display = display;         //遍历展示}function find(item){    var obj = this.head;    while(obj.element != item && obj != null){        obj = obj.next;    }    return obj;}function insert(cur,item){    var item = new Node(item);    var cur = this.find(cur);    if(cur){        item.next = cur.next;        cur.next = item;        item.pre = cur;        cur.next.pre = item;    }}function remove(item){    var item = this.find(item);    if(item.next != null){        item.pre.next = item.next;        item.next.pre = item.pre;        item.pre = null;        item.next = null    }}function display(){    var obj = this.head.next;    while(obj != null ){        console.log(obj.element);        obj=obj.next;    }}var list = new LinkedList();list.insert("head","monkey");list.insert("monkey","cat");list.insert("cat","mall");list.display();  //monkey cat malllist.remove("cat");list.display()  //monkey mall
原创粉丝点击