zoukankan      html  css  js  c++  java
  • 用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(根据指定的数据找到对应数据的结点,并删除)。

  • 相关阅读:
    并查集分析+总结
    poj 3083 Children of the Candy Corn(bfs+dfs 数组模拟方向)
    poj 1094 Sorting It All Out (拓扑排序)
    poj 2632 Crashing Robots(模拟)
    poj 1068 Parencodings (模拟)
    poj 1273 Drainage Ditches ( 最大流Edmonds_karp算法)
    poj 3278 Catch That Cow (BFS)
    Codeforces Round #109 (Div. 2) 总结
    poj 2299 UltraQuickSort(归并排序)
    poj 1035 Spell checker(字符串)
  • 原文地址:https://www.cnblogs.com/abab301/p/9617454.html
Copyright © 2011-2022 走看看