LeetCode: 剑指 Offer 24. 反转链表
双指针
递归 >> 也可以用 Stack
双指针
public ListNode
reverseList(ListNode head
) {
if(head
== null
|| head
.next
== null
) return head
;
ListNode slow
= head
, fast
= head
.next
;
slow
.next
= null
;
while (fast
!= null
){
ListNode temp
= fast
;
fast
= fast
.next
;
temp
.next
= slow
;
slow
= temp
;
}
return slow
;
}
head->next = null; >> 这个是为了让第一个节点最后指向 null, 否则会形成环