Algorithms first
反转链表 II · 交互式算法学习
只反转链表指定区间。
#92 · 链表
反转链表 II
Reverse Linked List II
head = [1,2,3,4,5], left = 2, right = 4链表3 个关键状态
步骤 1pre 在 1,cur 在 2。
pre=1,cur=21next
→2next
→3next
→4next
→5next
推荐
头插法原地反转
时间
O(n)空间 O(1)固定区间前驱,把区间后续节点逐个插到区间头部。
1function reverseBetween(head, l, r) {2 const d = {3 next: head4 };5 let pre = d;6 for (let i = 1; i < l; i++) pre = pre.next;7 let cur = pre.next;8 for (let i = 0; i < r - l; i++) {9 const move = cur.next;10 cur.next = move.next;11 move.next = pre.next;12 pre.next = move;13 }14 return d.next;15}多语言参考
来源 · CC BY-SA 4.0 ↗Java · C++ · Go
这是一组同题正确实现,独立于上方当前动画方法;不同语言可能采用另一种正确策略。
1/**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode next;6 * ListNode() {}7 * ListNode(int val) { this.val = val; }8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }9 * }10 */11class Solution {12 public ListNode reverseBetween(ListNode head, int left, int right) {13 if (head.next == null || left == right) {14 return head;15 }16 ListNode dummy = new ListNode(0, head);17 ListNode pre = dummy;18 for (int i = 0; i < left - 1; ++i) {19 pre = pre.next;20 }21 ListNode p = pre;22 ListNode q = pre.next;23 ListNode cur = q;24 for (int i = 0; i < right - left + 1; ++i) {25 ListNode t = cur.next;26 cur.next = pre;27 pre = cur;28 cur = t;29 }30 p.next = pre;31 q.next = cur;32 return dummy.next;33 }34}交互式算法学习
从执行步骤真正理解 LeetCode 经典 150
本站整理 150 道高频算法面试题和 302 种解法。动画方法同步展示 JavaScript 与 Python;每题另提供 Java、C++ 与 Go 同题参考实现。
AlgoViz Lab
反转链表 II · 解法对比
只反转链表指定区间。
- 测试用例
head = [1,2,3,4,5], left = 2, right = 4- 题目分类
- 链表
- 解法对比
- 2
取出区间后重连
把区间节点存入数组,逆序连接后接回前后部分。
- 时间
O(n)- 空间
O(k)
头插法原地反转
固定区间前驱,把区间后续节点逐个插到区间头部。
- 时间
O(n)- 空间
O(1)