反转链表
- 递归方式
只有一个节点或者空链表直接返回。
递归反转head->next,反转后只需将head->next->next = head, head.next = null即可。
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode node = reverseList(head.next);
head.next.next = head;
head.next = null;
return node;
}
}
- 迭代方式
依次反转相邻两个节点
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode a = head, b = head.next;
while (b != null) {
ListNode c = b.next;
b.next = a;
a = b;
b = c;
}
head.next = null;
return a;
}
}