javascript单链表

xiaoxiao2021-02-27  339

javascript中单向链表实现

    1.表头head,链表最后一个next指针为null;

    2.链表不存在数组的下表,关系只能通过上一个节点来找;

    3.链表优势,插入方便。

/**节点类*/ function Node(data){     this.data=data;     this.next=null; } /**链表类*/ function NodeList(){     this.head=new Node('head');     this.find=find,     this.insert=insert,     this.remove=remove,     this.print=print } /**链表查找,根据data数据查找*/ function find(data){     var cNode=this.head;     while(cNode&&cNode.data!=data){         cNode=cNode.next;     }     return cNode; } /**链表插入,在ddata处插入value*/ function insert(data,value){     var preNode=this.find(data);     var cNode=new Node(value);     cNode.next=preNode.next;     preNode.next=cNode; } /**获取当前节点的上一个节点*/ function _findPreNode(data){     var preNode=this.head;     while(preNode.next&&preNode.next.data!==data){         preNode=preNode.next;     }     if(!preNode.next){//没有找到,返回null         return null;     }else{         return preNode;//找到,返回上一个节点     } } /**链表删除*/ function remove(data){     var preNode=_findPreNode.call(this,data);//这个函数不是NodeList的属性,函数内的this不是NodeList对象实例,要用call改变上下文     var cNode=preNode.next;     preNode.next=cNode.next;     cNode.next=null;     return cNode; } /**打印单向链表*/ function print(){     var cNode=this.head.next;     while(cNode){         console.log(cNode.data);         cNode=cNode.next;     } }
转载请注明原文地址: https://www.6miu.com/read-1570.html

最新回复(0)