• 单向链表的实现


        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*/

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

  • 相关阅读:
    CSS同时选择器
    create-react-app之proxy
    mysql limit语句
    给tbody加垂直滚动条的具体思路
    MySql数据类型范围
    block、inline、inline-block
    javascript sourcemap
    session of express
    React中innerHTML的坑
    box-sizing
  • 原文地址:https://www.cnblogs.com/feile/p/5375547.html
Copyright © 2020-2023  润新知