1、力扣原题
https://leetcode-cn.com/problems/reverse-linked-list/
2、解题思路(递归)
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
// head.next : 4
// head.next.next : 4的next要指向5
// head.next: 5的next为null
head.next.next = head;
head.next = null;
return newHead;
}
}
2、解题思路(迭代)
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = null;
while (head != null) {
// 空盆交换法
ListNode tempListNode = head.next;
head.next = newHead;
newHead = head;
head = tempListNode;
}
return newHead;
}