递归与非递归写法
递归
var reverseList=function(head){
if(head===null||head.next===null) return head
if(head.next==null) return head//如果到了链表尾,返回head
var last=reverseList(head.next)//否则将节点反转
head.next.next=head
head.next=null
return last
}
非递归
var reverseList=function(head){
return reverseListHelp(head,null)
}
function reverseListHelp(curr,prev){
if(curr==null) return pre
var next=curr.next
curr.next=prev
return reverseListHelp(next,curr)
}
尾递归
var reverseListHelp=function(head){
return reverseListHelp(head,null)
}
function reverseListHelp(cur,pre){
if(cur===null) return pre//cur为空了,返回上一个节点,也就是尾节点
var next=cur.next
cur.next=pre//将当前节点的next指向前一个节点
return reverseListHelp(next,cur)
}