递归
head == null 和 head.next == null 不能交换位置,因为这样在链表为空时会报空指针异常,利用到了 || 的短路特性
public ListNode reverseList(ListNode head) {
// 第一个head是排除链表为空的情况
// 第二个head则是将链表的尾结点返回
if (head == null || head.next == null)
return head;
ListNode tempList = reverseList(head.next);
head.next.next = head;
// 这里是大坑,一定要记住写,不然leetcode会报出
// Error - Found cycle in the ListNode,链表有环
head.next = null;
return tempList;
}
非递归
public ListNode reverseList(ListNode head) {
ListNode pre = null;
while (head != null) {
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}