双向链表
来源:互联网 发布:悍将传世源码 编辑:程序博客网 时间: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
阅读全文
0 0
- SzNOI 双向约瑟夫(双向链表)
- 双向链表&&堆栈
- 双向链表
- 使用双向链表
- 双向链表
- 双向循环链表
- 双向循环链表
- 双向链表
- 实现双向链表
- 双向循环链表
- 建立双向链表
- 双向链表
- 双向链表
- 双向循环链表
- 双向链表
- 链表-双向链表
- 双向链表
- 双向动态链表
- 包 package
- [Lintcode] 105. Copy List with Random Pointer
- 数据结构与算法常见笔试题
- 百练1321:棋盘问题
- Eclipse Oxygen创建第一个Hibernate 5程序
- 双向链表
- Android零基础入门第61节:滚动视图ScrollView
- Tensorflow Model Persistence
- JS回调函数中无法改变外部变量的问题
- 关于C++构造与析构函数
- 【LeetCode】27. Remove Element
- JAVA工具类(12)---文本字符串工具类(数据替换,加密解密操作)
- 正则表达式 元字符
- UGUI 按钮事件案例