我对下面的函数有疑问,该函数将 LinkedList 分成两个大小相等的列表。我理解对于“慢”列表,我们如何迭代原始列表,直到“快”为空(那时,“慢”将遍历列表的一半)。但是,我不明白“head”如何仅成为列表的前半部分。我在代码中没有看到直接修改 head 的任何地方。如果这是一个幼稚的问题,我深表歉意——LinkedLists 的新手!
function splitLL(head) {
let prev = null;
let slow = head;
let fast = head;
while(fast !== null && fast.next !== null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null
console.log("This is first half", head);
console.log("This is second half", slow);
}
最佳答案
不需要修改 head,因为原始列表的头部仍然是较短列表之一的头部。例如,如果原始列表是:
head -> node1 -> node2 -> node3 -> null
分解的列表现在将是
head -> node1 -> null
node2 -> node3 -> null
原来的磁头不需要修改。这有点像把绳子切成两半。其中一半的起点是整根绳索的原始起点。
关于javascript - 分割链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52674432/