双指针
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
while (cur != null) {
ListNode tempNext = cur.next;
cur.next = prev;
prev = cur;
cur = tempNext;
}
return prev;
}
}
递归
class Solution {
public ListNode reverseList(ListNode head) {
// 和双指针法初始化是一样的逻辑
// ListNode* cur = head;
// ListNode* pre = NULL;
return reverse(null, head);
}
private ListNode reverse(ListNode prev, ListNode cur) {
if (cur == null) return prev;
ListNode tempNext = cur.next;
cur.next = prev;
// 可以和双指针法的代码进行对比,如下递归的写法,其实就是做了这两步
// pre = cur;
// cur = temp;
return reverse(cur, tempNext);
}
}