zoukankan      html  css  js  c++  java
  • JS 链表

    链表

    定义

    • 是一组节点的集合
    • 每个节点都使用一个对象的引用来指向的后继
    • 每个节点的引用叫做链表

    和数组的不同

    • 数组靠它的位置来指向他的引用
    • 链表则靠他们相互之间的关系进行引用

    链表的抽象定义

    • 元素值
    • 指向下一个节点的引用
    • 指向上一个节点的引用

    双向链表的实现

    function Node(element) {
        this.element = element;
        // 下一节点
        this.next = null;
        // 上一节点
        this.prev = null;
    }
    
    
    function Linklist() {
        this.head = new Node("head");
    
        this.insert = insert;
        this.remove = remove;
        this.find = find;
        this.display = display;
        this.findPreNode = findPreNode;
    }
    
    function find(element) {
        var curNode = this.head;
        console.log(curNode);
        while (curNode.element != element) {
            curNode = curNode.next;
        }
        return curNode;
    }
    
    function insert(newEl, oldEl) {
        var newNode = new Node(newEl);
    
        var curNode = this.find(oldEl);
        newNode.next = curNode.next
        newNode.preNode = curNode;
        curNode.next = newNode;
    
    
    }
    
    
    function display() {
        var headNode = this.head;
        var resMsg = "";
        while (headNode.next != null) {
            resMsg += headNode.element + ",";
            headNode = headNode.next;
        }
        return resMsg;
    }
    
    
    function remove(element) {
        var curNode = this.find(element);
        if (curNode != null) {
            curNode.prev.next = curNode.next;
            curNode.next.prev = curNode.prev;
            curNode.prev = null;
            curNode.next = null;
        }
    }
    
    function findPreNode(element) {
        var curNode = this.head;
        while (curNode.next != null && curNode.next.element != element) {
            curNode = curNode.next;
        }
        return curNode;
    }
    
    function findLast() {
        var curNode = this.head;
        while (curNode.next != null) {
            curNode = curNode.next;
        }
        return curNode;
    }
    

    循环列表,将头节点的

    this.head.next=this.head;
  • 相关阅读:
    HDOJ 2095 find your present (2)
    HDOJ 2186 悼念512汶川大地震遇难同胞——一定要记住我爱你
    九度 1337 寻找最长合法括号序列
    九度 1357 疯狂地Jobdu序列
    HDOJ 1280 前m大的数
    九度 1343 城际公路网
    九度 1347 孤岛连通工程
    HDOJ 2151 Worm
    九度 1342 寻找最长合法括号序列II
    九度 1346 会员积分排序
  • 原文地址:https://www.cnblogs.com/dark-liu/p/5796919.html
Copyright © 2011-2022 走看看