zoukankan      html  css  js  c++  java
  • 单向链表的实现

        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 + "<br />");
                currNode = currNode.next;
            }
        }
        var cities = new LList();
        cities.insert("Conway", "head");
        cities.insert("Russellville", "Conway");
        cities.insert("Alma", "Russellville");
        cities.display();
        document.write("*********" + "<br />");
        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*/

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

  • 相关阅读:
    class 类添加属性
    Ajax请求数据data被JSON.stringify()的数据django解码过程
    Python之浏览器的前进或后退
    滚动条-智能等待-富文本
    Python之阶乘代码
    Python之用型号构成一个三角形代码
    C# Dictionary
    使用C#创建Windows服务
    sql取出每月最早的上报的数据
    mvc NPOI导入读取Excel文件
  • 原文地址:https://www.cnblogs.com/feile/p/5375547.html
Copyright © 2011-2022 走看看