【JavaScript数据结构与算法】链表
链表
1 数组的缺点
JavaScript数组不存在添加删除元素需要将剩下元素前后移动的问题,但由于被实现成了对象,所以与其他语言相比,效率很低。除了对数据的随机访问,链表几乎可以用在任何可以使用一维数组的情况中。
2 定义链表
链表:由一组节点组成的集合。每个节点都使用一个对象的引用指向它的后继。指向另一个节点的引用叫做链。 许多链表的实现都在链表的最前面有一个特殊节点,叫做头节点。链表的尾元素指向一个null元素。
3 设计一个基于对象的链表
包含两个类:Node类表示节点 LinkedList类提供了插入节点、删除节点、显示列表元素等方法。
3.1 Node类
function Node(element){ this.element=element;//当前元素 this.next=null;//指向后继 }
3.2 LinkedList类
一个属性Node对象用于保存该链表的头节点。
function LList(){ this.head=new Node("head"); this.find=find; this.insert=insert;//插入 this.remove=remove;//删除 this.display=display;//显示链表 }
3.2.1 插入新节点
辅助方法find():返回内容为item的节点。如果查找成功, 该方法返回包含该数据的节点; 否则, 返回 null。
function find(item){ var curNode=this.head;//头节点 while(curNode&&(curNode.element!=item)){ curNode=curNode.next; } return curNode; } function insert(newElement,item){//在item后面插入newElement var newNode=new Node(newElement);//构造新节点 var current=this.find(item); newNode.next=current.next; current.next=newNode; } function display(){ var curNode=this.head; while(!(curNode.next==null)){ console.log(curNode.next.element); curNode=curNode.next; } }
3.2.2 删除节点
function remove(item){ var curNode=this.head; var itemNode=this.find(item); while(curNode.next!=null&&curNode.next.element!=item){ curNode=curNode.next; } if(itemNode.next!=null){ curNode.next=itemNode.next; } }
4 双向链表
为了使从后向前遍历更简单,通过给Node增加一个属性,存储指向前驱节点的链接。
function Node(element){ this.element=element; this.next=null; this.previous=null; } function insert(newElement,item){ var newNode=new Node(newElement); var current=this.find(item); newNode.next=current.next; current.next=newNode; newNode.previous=current; if(newNode.next){ newNode.next.previous=newNode; } } function remove(item){ var curNode=this.find(item); if(curNode.next!=null){ curNode.previous.next=curNode.next; curNode.next.previous=curNode.previous; curNode.previous=null; curNode.next=null; } }
为了完成反向遍历链表,就像得到头节点一样,需要得到最后一个节点。
function findLast(){ var curNode=this.head; while(curNode.next!=null){ curNode=curNode.next; } return curNode; } function displayReverse(){ var curNode=this.findLast(); while(curNode.previous!=null){ console.log(curNode.element); curNode=curNode.previous; } } function LList(){ this.head=new Node(head); this.find=find; this.insert=insert; this.display=display; this.remove=remove; this.findLast=findLast; this.displayReverse=displayReverse; }
5 循环链表
循环链表和单向链表相似,节点类型都是一样的。唯一的区别是,在创建循环链表时,让其头节点的next属性指向其本身。这个行为会传导至链表中的每个节点,使每个节点的next属性最终都指向链表的头节点。 LList构造函数中只需要添加this.head.next=this.head即可,插入的节点next指针都要指向head节点。