1.问题描述
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
2.测试用例
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
3.提示
- 链表中节点的数目范围是 [0, 5000]
- -5000 <= Node.val <= 5000
4.代码
1.迭代
code
public ListNode reverseListWithLoop(ListNode head) {
ListNode prev = null;
ListNode current = head;
ListNode next;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
复杂度
时间 O(n)
空间 O(1)
2. 递归
code
public ListNode reverseListWithRecursion(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode reversedRest = reverseListWithRecursion(head.next);
head.next.next = head;
head.next = null;
return reversedRest;
}
复杂度
时间 O(n)
空间 O(n)