使用JavaScript实现链表的数据结构的代码
链表(Linkedlist)是一种常见的基础数据结构,是一种线性表,但是并不会按线性的顺序存储数据,而是在每一个节点里存到下一个节点的指针(Pointer) —维基百科
上面是维基百科对链表的解读。下面我们用JavaScript代码对链表的数据结构进行实现
实现Node类表示节点
/**
*Node类用来表示节点
*element用来保存节点上的数据
*next用来保存指向下一个节点的链接
*/
functionNode(element){
this.element=element;
this.next=null;
}
LList类提供对链表操作的方法
/**
*LList类提供了对链表进行操作的方法
*链表只有一个属性,
*使用一个Node对象来保存该链表的头节点。
*/
classLList{
constructor(){
this.head=newNode('head');
}
//查找节点
find(item){
letcurrNode=this.head;
while(currNode.element!==item){
currNode=currNode.next;
}
returncurrNode;
}
//查找前一个节点
findPre(item){
if(item==='head')thrownewError('nowishead!');
letcurrNode=this.head;
while(currNode.next&&currNode.next.element!==item){
currNode=currNode.next;
}
returncurrNode;
}
//插入新节点
insert(newElement,item){
letnewNode=newNode(newElement);
letcurrNode=this.find(item);
newNode.next=currNode.next;
currNode.next=newNode;
}
//删除一个节点
remove(item){
letpreNode=this.findPre(item);
if(preNode.next!==null){
preNode.next=preNode.next.next;
}
}
//显示链表中的元素
display(){
letcurrNode=this.head;
while(currNode.next!==null){
console.log(currNode.next.element);
currNode=currNode.next;
}
}
}
测试代码
constlist=newLList();
//LList{head:Node{element:'head',next:null}}
list.insert('0','head');
list.insert('1','0');
list.insert('2','1');
list.insert('3','2');
list.remove('1');
console.log(list);
//LList{head:Node{element:'head',next:Node{element:'0',next:[Object]}}}
console.log(list.display());//023
console.log(list.findPre('1'));
//Node{element:'0',next:Node{element:'1',next:Node{element:'2',next:[Object]}}}
上面就是用JavaScript对简单链表的数据结构的简单实现:smile:
总结
以上所述是小编给大家介绍的使用JavaScript实现链表的数据结构的代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!