Algorithms first
分隔链表 · 交互式算法学习
保持相对顺序,把小于 x 的节点放在其余节点之前。
#86 · 链表
分隔链表
Partition List
head = [1,4,3,2,5,2], x = 3链表3 个关键状态
步骤 11 接入 small,4、3 接入 large。
small=[1],large=[4,3]1next
→4next
→3next
→2next
→5next
→2next
推荐
两条临时链表
时间
O(n)空间 O(1)扫描时直接把节点接入 small 或 large 链尾,最后拼接。
1function partition(head, x) {2 const sd = {3 next: null4 },5 ld = {6 next: null7 };8 let s = sd,9 l = ld;10 while (head) {11 const next = head.next;12 head.next = null;13 if (head.val < x) {14 s.next = head;15 s = head16 } else {17 l.next = head;18 l = head19 }20 head = next;21 }22 s.next = ld.next;23 return sd.next;24}多语言参考
来源 · 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 partition(ListNode head, int x) {13 ListNode l = new ListNode();14 ListNode r = new ListNode();15 ListNode tl = l, tr = r;16 for (; head != null; head = head.next) {17 if (head.val < x) {18 tl.next = head;19 tl = tl.next;20 } else {21 tr.next = head;22 tr = tr.next;23 }24 }25 tr.next = null;26 tl.next = r.next;27 return l.next;28 }29}交互式算法学习
从执行步骤真正理解 LeetCode 经典 150
本站整理 150 道高频算法面试题和 302 种解法。动画方法同步展示 JavaScript 与 Python;每题另提供 Java、C++ 与 Go 同题参考实现。
AlgoViz Lab
分隔链表 · 解法对比
保持相对顺序,把小于 x 的节点放在其余节点之前。
- 测试用例
head = [1,4,3,2,5,2], x = 3- 题目分类
- 链表
- 解法对比
- 2
数组稳定分组后重建
分别收集小值与大值节点,再顺序连接。
- 时间
O(n)- 空间
O(n)
两条临时链表
扫描时直接把节点接入 small 或 large 链尾,最后拼接。
- 时间
O(n)- 空间
O(1)