给文章中的h标签生成目录结构(巧妙利用双向链表数据结构)
硅谷探秘者
2020-10-10发表
0
0
1844
1.前言
例如在用富文本编辑器编辑文章的时候,会用到h标签来代表本段标题,那么h标签是有顺序的,例如:
h标签的顺序可能是这样的
h1
h1
h2
h3
h1
h3
h2
h4
那么目录结构就应该是
那么目录结构应该是
h2
h1
----h2
--------h3
h1
----h3
----h2
--------h4
2.案例如图:

本文就介绍如何使用js设计数据结构,巧妙利用双向链表实现将顺序的目录,转换成树状目录。
3.js代码
<script>
/**
* 链表节点信息
**/
function Node(data){
this.data=data;
this.next=null;
this.prev=null;
}
/**
* 双向链表数据结构
**/
function LinkedList(){
this.head=null;
this.tail=null;
/**
* 添加节点(添加的节点是尾节点)
**/
this.add=function(data){
var node=new Node(data);
if(this.head==null){
this.head=this.tail=node;
}else{
node.prev=this.tail;
this.tail.next=node;
this.tail=node;
}
}
/**
* 删除目标节点
**/
this.delete=function(node){
if(node==null){
return null;
}
if(node==this.head&&node==this.tail){
this.head=null;
this.tail=null;
}else if(node==this.head){
this.head=this.head.next;
this.head.prev=null;
}else if(node==this.tail){
this.tail=this.tail.prev;
this.tail.next=null;
}else{
node.prev.next=node.next;
node.next.prev=node.prev;
}
node.next=null;
node.prev=null;
return node;
}
}
/**
* 数据节点信息
**/
function createNode(name,level){
return {
name:name, //名称
level:level, //标签级别
child:new Array(), //标签子节点
};
}
/**
* 生成链表和树的组合结构
**/
function create(h,arr){
while(h!=null){
var li=new LinkedList();
while(h.next!=null){
if(h.next.data.level>h.data.level){
li.add(arr.delete(h.next).data)
}else {
break;
}
}
/**
* 递归生成子树
**/
create(li.head,li);
h.data.child=li;
h=h.next;
}
}
/**
* 将组合结构中的链表结构转换为数组结构
**/
function toArray(arr){
var a=new Array();
var h=arr.head;
while(h!=null){
if(h.data.child!=null){
h.data.child=toArray(h.data.child);
}
a.push(h.data);
h=h.next;
}
return a;
}
/**
* 模拟h标签
**/
var array=new LinkedList();
array.add(createNode("h2",2));
array.add(createNode("h3",3));
array.add(createNode("h2",2));
array.add(createNode("h1",1));
array.add(createNode("h3",3));
array.add(createNode("h2",2));
array.add(createNode("h2",2));
array.add(createNode("h3",3));
array.add(createNode("h3",3));
array.add(createNode("h4",4));
create(array.head,array);//生成树结构
var data=JSON.stringify(toArray(array));//转化json
/**
* 打印数据
**/
console.log(data)
</script>
本js只是模拟用顺序的h标签,生成树状的json数据结构,代码多处涉及递归算法
具体html+js+css实现请参考:http://jiajiajia.club/blog/artical/vSdf1Q/406