迭代
var reverseList = function(head) {
// 1.一层一层往前指,就是把后边的next指向前边
if(!head){return head}
var item = head
var pre = null
var next = head.next
while(1){
item.next = pre
pre = item
item = next
if(!item){
break
}
next = next.next
}
return pre
};
递归
var reverseList = function(head) {
// 2. 递归:认为dp函数返回的是已经倒序好的后面链表,这时只需要把倒序好的后边链表头指向前一个就可以了,再返回前一个作为新的倒序链表头
if(!head){return head}
var res
function dp(nk){
if(!nk.next){
res = nk
return nk
}
var nkNext = dp(nk.next)
nkNext.next = nk
return nk
}
var h = dp(head)
h.next = null
return res
};