【发布时间】:2016-11-07 20:21:21
【问题描述】:
问题来自 Leetcode。
“给定一个链表和一个值 x,对它进行分区,使得所有小于 x 的节点都在大于或等于 x 的节点之前。 您应该保留两个分区中每个分区中节点的原始相对顺序。”
我的问题是,为什么我们必须有“right.next = null”这一行。如果我不将 NULL 放在 LinkedList 的末尾,为什么它会给出“超出内存限制错误”? 提前致谢!
public ListNode partition (ListNode head, int x) {
if (head==null) return head;
ListNode leftDummy = new ListNode(0);
ListNode rightDummy = new ListNode(0);
ListNode left = leftDummy;
ListNode right = rightDummy;
while (head!=null) {
if (head.val < x) {
left.next = head;
left = head;
} else {
right.next = head;
right = head;
}
head = head.next;
}
// merge the two
right.next = null; // WHY THIS LINE??
left.next = rightDummy.next;
return leftDummy.next;
}
【问题讨论】:
-
如果你没有对原始列表进行分区,所以我的猜测是当你合并它们时,你正在创建 N^2 的节点数。这就是使用调试器有助于解释您做得更好的地方。
标签: java memory-leaks linked-list