博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
单向链表的实现
阅读量:4574 次
发布时间:2019-06-08

本文共 2026 字,大约阅读时间需要 6 分钟。

function Node(element) {        this.element = element;// element 用来保存节点上的数据        this.next = null;//用来保存指向下一个节点的链接    }    function LList() {        this.head = new Node("head");        this.find = find;        this.insert = insert;        //this.remove = remove;remove()若是未定义会出错!!必须注释掉        this.findPrevious = findPrevious;        this.remove = remove;        this.display = display;    }    function find(item) {        var currNode = this.head;        while (currNode.element != item) {            currNode = currNode.next;        }        return currNode;    }    function insert(newElement, item) {
//在item节点后插入newElement新节点 var newNode = new Node(newElement);//插入元素必先创建节点 var current = this.find(item); //添加元素不需要考虑item不存在的情况,因为当item不存在时,可在链表末尾添加 newNode.next = current.next;//用链表的思想去考虑,不要从赋值的角度考虑 //node.next()可看作指向下一个节点的链接&&下一个节点 //理解为链接指向新节点,newNode.next链接指向current.next节点 current.next = newNode;//此处断开原链接 } function display() { var currNode = this.head; while (!(currNode.next == null)) { document.write(currNode.next.element + "
"); currNode = currNode.next; } } var cities = new LList(); cities.insert("Conway", "head"); cities.insert("Russellville", "Conway"); cities.insert("Alma", "Russellville"); cities.display(); document.write("*********" + "
"); function findPrevious(item) { //删除元素需要找到该元素前面的节点 var currNode = this.head; while ((currNode.next.element != item)) { currNode = currNode.next; } return currNode; } function remove(item) { var prevNode = this.findPrevious(item); if (prevNode.next != null) { prevNode.next = prevNode.next.next; } } cities.insert("lelei", "Alma"); cities.remove("Alma"); cities.display(); /* 上述程序运行结果如下: Conway Russellville Alma ********* Conway Russellville lelei*/

关于添加节点的图示理解:

转载于:https://www.cnblogs.com/feile/p/5375547.html

你可能感兴趣的文章
MySQL_入手<二>之删--改--查
查看>>
MySQL创表--分页--自关联--
查看>>
python基础_面向对象进阶
查看>>
GitHub从小白到熟悉<一>
查看>>
软件测试员常踩的7个坑,不想再入坑者必看
查看>>
测试基础_<一>
查看>>
前端基础进阶(三):变量对象详解
查看>>
[算法]Collebarative Filtering
查看>>
clientX,screenX,pageX,offsetX的异同
查看>>
c# in out ref关键字
查看>>
day 30 客户端获取cmd 命令的步骤
查看>>
笔记javascript
查看>>
Distinct
查看>>
SQL 循环语句
查看>>
定义页面加载和导航时要执行的函数/自定义事件
查看>>
rem.js
查看>>
Unslider.js Tiny Sample
查看>>
FPGA的学习及注意事项
查看>>
面向对象内存分析
查看>>
Dijkstra BZOJ2763 [JLOI2011]飞行路线
查看>>