数据结构之链表篇——JavaScript语言实现_数据结构





在数据结构的学习中,动态链表是动态数据结构的最基本的形式,也是最常见的一种线性数据结构,使用范围广。




在创建动态链表时,对不同节点之间的链接关系梳理清楚,这一点十分重要。。。






比如,下面开始试着用JavaScript编程语言来实现基本的链表操作,包括:


  1. 在动态链表中插入节点
  2. 在动态链表中删除节点
  3. 求动态链表的长度
  4. 打印输出动态链表的全部元素 






动态链表的节点,可以按如下方式定义:




数据结构之链表篇——JavaScript语言实现_数据结构_02








// 作者:文方俊
// 日期:2020年11月28日


class Node
{
constructor(value){
this.value = value;
this.next = null;
};
};




动态链表中插入节点,




// 作者:文方俊
// 日期:2020年11月28日
insertNode(value){
var newNode = new Node(value);
if (null == this.head){
this.head = newNode;
} else {
newNode.next = this.head;
this.head = newNode;
}
return null;
};




动态链表中删除节点,





// 作者:文方俊
// 日期:2020年11月28日
deleteNode(value){
var deleteNode = null;
// 链表为空
if (null == this.head){
return null;
} else {
// 删除头节点
if (value == this.head.value){
deleteNode = this.head;
this.head = this.head.next;
} else {
var pre = this.head;
while ((null!=pre.next) && (value != pre.next.value)){
pre = pre.next;
}
if (null === pre.next){
return null;
}
if (value == pre.next.value){
deleteNode = pre.next;
pre.next = pre.next.next;
}
}
};
return deleteNode;
};




打印输出动态链表,







// 作者:文方俊
// 日期:2020年11月28日
printLinkedList(){
var tmp = this.head;
var values = [];
while (null != tmp){
values.push(tmp.value);
tmp = tmp.next;
}
return values;
}





计算动态链表的长度,





// 作者:文方俊
// 日期:2020年11月28日
length(){
var tmp = this.head;
var len_list = 0;
while (null != tmp){
len_list+=1;
tmp = tmp.next;
}
return len_list;
};





动态链表的完整代码实现,可以参考下面的JavaScript程序,



// LinkedList.js 
// 作者:文方俊
// 日期:2020年11月28日


class Node
{
constructor(value){
this.value = value;
this.next = null;
};
};


class LinkedList
{
insertNode(value){
var newNode = new Node(value);
if (null == this.head){
this.head = newNode;
} else {
newNode.next = this.head;
this.head = newNode;
}
return null;
};
deleteNode(value){
var deleteNode = null;
// 链表为空
if (null == this.head){
return null;
} else {
// 删除头节点
if (value == this.head.value){
deleteNode = this.head;
this.head = this.head.next;
} else {
var pre = this.head;
while ((null!=pre.next) && (value != pre.next.value)){
pre = pre.next;
}
if (null === pre.next){
return null;
}
if (value == pre.next.value){
deleteNode = pre.next;
pre.next = pre.next.next;
}
}
};
return deleteNode;
};
length(){
var tmp = this.head;
var len_list = 0;
while (null != tmp){
len_list+=1;
tmp = tmp.next;
}
return len_list;
};
printLinkedList(){
var tmp = this.head;
var values = [];
while (null != tmp){
values.push(tmp.value);
tmp = tmp.next;
}
return values;
}
constructor(){
this.head = null;
};
};










数据结构之链表篇——JavaScript语言实现_动态链表_03




数据结构之链表篇——JavaScript语言实现_javascript_04





关注“AI早知道”公众号二维码,更多精彩下回待续。。。





数据结构之链表篇——JavaScript语言实现_动态链表_05


        遇见爱or遇见自己or遇见幸福,      

 再出发,

遇见更精彩的自己 

         。。。