| title | 206. 反转链表 | |||||||
|---|---|---|---|---|---|---|---|---|
| description | LeetCode 206. 反转链表题解,Reverse Linked List,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。 | |||||||
| keywords |
|
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
Constraints:
- The number of nodes in the list is the range
[0, 5000]. -5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
有两种解题方法,一是循环、二是递归。
使用双指针,遍历链表,并在访问各节点时修改 next 引用指向。
- 时间复杂度:
O(n),遍历链表使用线性大小时间。 - 空间复杂度:
O(1),变量prev和cur使用常数大小额外空间。
使用递归法遍历链表,当越过尾节点后终止递归,在回溯时修改各节点的 next 引用指向。
- 时间复杂度:
O(n),遍历链表使用线性大小时间。 - 空间复杂度:
O(n),遍历链表的递归深度达到n,系统使用O(n)大小额外空间。
::: code-tabs
@tab 循环
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function (head) {
let prev = null;
let cur = head;
while (cur !== null) {
let next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
};@tab 递归
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function (head) {
if (head === null || head.next === null) {
return head;
}
const last = reverseList(head.next);
head.next.next = head;
head.next = null;
return last;
};:::
| 题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
|---|---|---|---|---|---|
| 92 | 反转链表 II | [✓] | 链表 |
🟠 | 🀄️ 🔗 |
| 156 | 上下翻转二叉树 🔒 | [✓] | 树 深度优先搜索 二叉树 |
🟠 | 🀄️ 🔗 |
| 234 | 回文链表 | [✓] | 栈 递归 链表 1+ |
🟢 | 🀄️ 🔗 |
| 2074 | 反转偶数长度组的节点 | 链表 |
🟠 | 🀄️ 🔗 | |
| 2130 | 链表最大孪生和 | [✓] | 栈 链表 双指针 |
🟠 | 🀄️ 🔗 |
| 2487 | 从链表中移除节点 | 栈 递归 链表 1+ |
🟠 | 🀄️ 🔗 | |
| 2807 | 在链表中插入最大公约数 | 链表 数学 数论 |
🟠 | 🀄️ 🔗 |

