JS链表逆置
思路图解
先定位到倒数第二个节点,之后:
1.将后一节点的next改成本节点
2.取消本节点的next
3.返回末尾节点
之后依次对倒数第三个节点进行上述1和2的操作,注意需要用一个变量保存每一次修改后的链表,最后返回出去
做题思维
1.先写函数的出口,即返回值
2找出重复的操作是什么
3.如何到达下一个递归
//创建一个链表
function Node(value){
this.value=value
this.next=null
}
let a=new Node(1)
let b=new Node(2)
let c=new Node(3)
let d=new Node(4)
a.next=b
b.next=c
c.next=d
//链表逆置(参数是链表根节点,返回值是逆置后的链表的根节点)
function reverse(root){
if(root.next.next===null){
root.next.next=root
root.next.null
return root.next
}else{
let result=reverse(root.next)
root.next.next=root
root.next=null
return result
}
}
//递归遍历
function travel(root){
if(root===null) return
console.log(root.value)
travel(root.next)
}
travel(reverse(a))