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

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

  • 相关阅读:
    黑板客爬虫闯关 代码
    新浪云SAE搭建python环境 问题拾遗
    关于python中的字符串编码理解
    linux环境中使用转义字符使命令行字符颜色高亮
    python中list作为全局变量无需global声明的原因
    获取youku视频下载链接(wireshark抓包分析)
    改变linux默认配色方案(dircolors和dircolors-solarized使用)
    限流常规设计和实例
    连接池-Mybatis源码
    Transaction-Mybatis源码
  • 原文地址:https://www.cnblogs.com/feile/p/5375547.html
Copyright © 2011-2022 走看看