• 用js实现简单链表


      今天偶然想起一直以来使用传统面向对象的编程语言比如C++、java等实现的---链表----数据结构是不是也可以用js实现?至少之前看到过用js实现二叉树的代码,但是js实现的二叉树简直丑陋。。。。(用数组实现的)。

      直接上代码

    (function(window){
      //Node结点类
    var Node=function(data){ this.data=data; this.next=null; this.getNext=function(){ return this.next; } } Node.prototype.nextNode = function(){ if(this.next===null) return; if(this.next instanceof Node){ return this.next; } }; Node.prototype.addNode=function(node){ this.next=node; };   //链表类 function LinkList(){ this.head=new Node(0); this.currentNode=this.head; }; LinkList.prototype.add=function(node){ this.currentNode.addNode(node); this.currentNode=this.currentNode.nextNode(); }; LinkList.prototype.deleteNode=function(data){ var pre=this.head; var _node=this.head.nextNode(); // console.log("prev "); // console.log(pre); // console.log("_node "); // console.log(_node); while(_node!=null){ if(_node.data===data) break; pre=pre.nextNode(); _node=_node.nextNode(); } pre.addNode(_node.getNext()); this.currentNode=_node.getNext(); }; LinkList.prototype.show=function(){ let item=this.head.nextNode(); console.log(item); while(item!=null){ console.log('data= '+item.data+';'); item=item.nextNode(); } };
       //主函数 (
    function(){ var linklist=new LinkList(); var arr=[1,2,3,4,5]; for(var i=0,length=arr.length;i<length;i++){ linklist.add(new Node(arr[i])); } linklist.show(); linklist.deleteNode(3); linklist.show(); }()) })(window)

    结果如下:(chrome控制台)

      上面的代码中只实现了简单的链表功能,比如增加Node、删除Node(根据指定的数据找到对应数据的结点,并删除)。

  • 相关阅读:
    html 简介
    MySQL事务等了解知识
    MySQL—navicat&&练习&&pymysql
    MySQL查询表(一)
    作业
    MySQL约束&&表关系
    mysql数据类型
    初识mysql
    dll 原理解析
    又过了一天
  • 原文地址:https://www.cnblogs.com/abab301/p/9617454.html
Copyright © 2020-2023  润新知