//链表是线性结构
//单向链表 (每个节点都有一个next属性指向下一个 头指向第一个元素)
//单向循环链表 (最后一个节点 指向头部)
//双向链表(两个指针 分别指向前一个和后一个)
//双向循环链表(两个指针 分别指向前一个后后一个,第一个的前一个指向尾,最后一个的后一个指向头)
//循环链表 最后一个元素的next 指向 其他节点
//优点:从头和尾 取值 性能高 存放数据 平均查询的复杂度(On)
//js垃圾回收 是靠指针是否有引用关系
//基于链表可以封装队列 没有数组塌陷问题
class Node{
constructor(element,next){
this.element = element
this.next = next
}
}
class LinkList{
constructor(){
this.head = null //链表的头部
this.size = 0 //链表的长度
}
add(index,elemnet){
if(arguments.length === 1){
// 想后面添加
elemnet = index //如果只有一个参数 传入的就是元素
index = this.size
}
if(index < 0 || index >this.size) throw new Error('报错')
if(index === 0){
let head = this.head //原来的头
//设置新的头部,将老的头变成,下一个节点
this.head = new Node(elemnet,head)
}else{
//先找到当前索引的上一个
let prevNode = getNode(index-1)
//将上一个节点指向当前这个,将当前这个节点的next上指向原来上一个节点的next
prevNode.next = new Node(elemnet,prevNode.next)
}
this.size ++
}
getNode(index){
let current = this.head;
for (let i = 0; i < index; i++) {
current = current.next
}
return current
}
get(){
}
remove(){
}
//递归实现
reversLinkList(){
const revers = (head) => {
//只有一个 或者后面有元素来 就不反转来
if( head ===null || head.next === null ){
return head
}
//在执行栈中一个一个压进去,直到压倒最后一个 开始执行 下面到交换
let newHead = revers(head.next)
head.next.next = head
head.next = null;
return newHead
}
revers(this.head)
return this.head
}
//循环实现 链表反转
reversLinkList1(){
let head = this.head;//获取第一个元素
if( head ===null || head.next === null ){
return head
}
let newHead = null
//循环交换这些值
while(head != null){
let temp = head.next // 先保存下一个
head.next = newHead //当前这一项 的next 指向上一个
newHead = head //将上一个元素 变成head
head = temp // 将head 变成缓存下来的 下一个
}
this.head = newHead
return this.head
}
}