首页 > Web开发 > 详细

js:数据结构笔记5--链表

时间:2014-10-17 13:18:04      阅读:282      评论:0      收藏:0      [点我收藏+]

数组:

  • 其他语言的数组缺陷:添加/删除数组麻烦;
  • js数组的缺点:被实现为对象,效率低;
  • 如果要实现随机访问,数组还是更好的选择;

链表:

  • 结构图:

bubuko.com,布布扣

  • 基本代码:
    function Node (elem) {
       this.elem = elem;
       this.next = null;
    }
    function LList() {
       this.head = new Node("head");
       this.find = find;
       this.insert = insert;
       this.findPrevious = findPrevious;
       this.remove = remove;
       this.display = display;
    }
    
    function find(item) {
       var currNode = this.head;
       while(currNode.elem !== item) {
          currNode = currNode.next;
       }
       return currNode;
    }
    function insert(newElem,item) {
       var newNode = new Node(newElem);
       var currNode = this.find(item);
       newNode.next = currNode.next;
       currNode.next = newNode;
    }
    function display() {
       var currNode = this.head;
       while(!(currNode.next === null)) {
          console.log(currNode.next.elem);
          currNode = currNode.next;
       }
    }
    function findPrevious(item) {
       var currNode = this.head;
       while(!(currNode.next === null) && (currNode.next.elem !== item)) {
          currNode = currNode.next;
       }
       return currNode;
    }
    function remove(item) {
       var prevNode = this.findPrevious(item);
       if(!(prevNode.next === null)) {
          prevNode.next = prevNode.next.next;
       }
    }

操作:demo;

 

js:数据结构笔记5--链表

原文:http://www.cnblogs.com/jinkspeng/p/4030681.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!