[英]Java implementation of Merge Sort for Linked List splitting issue
I've been looking at merge sort implementation in Java and don't understand the following part: 我一直在寻找Java中的合并排序实现,但不了解以下内容:
Node middle = getMiddle(head); //get the middle of the list
Node left_head = head;
Node right_head = middle.next;
middle.next = null; //split the list into two half's
So by setting middle.next = null we split left_head by the middle. 因此,通过设置middle.next = null,我们将left_head除以中间位置。 But why right_head remains in place since it refers to middle.next which became null ?
但是,为什么right_head仍然指向原处,因为它引用了成为null的 middle.next ?
UPDATE: Ok, so what got me confused here is that middle.next = null
doesn't actually sets next Node as a null, but updates middle's
next variable to null , which of course doesn't affect right_head
. 更新:好的,所以让我感到困惑的是
middle.next = null
实际上并没有将next Node设置为null,而是将middle's
next变量更新为null ,这当然不会影响right_head
。
If you carefully observe the code segment you've posted, you'll see that the code executes line by line in this case. 如果您仔细观察所发布的代码段,在这种情况下,您将看到代码逐行执行。 Following is a step by step description :
以下是分步说明:
1) middle
is set to point to the middle most node. 1)
middle
设置为指向最中间的节点。
2) left head
points to the first node in the left part of the split. 2)
left head
指向拆分左侧的第一个节点。
3) right head
points to the first node in the right part of the split, which is actually the next to the middle node. 3)
right head
指向分割右边部分中的第一个节点,实际上是中间节点的下一个节点。
4) when middle.next
is set to null, the chaining of nodes is broken and the linked list splits into two halves, where left_head
and right_head
, point to the corresponding left and right segments. 4)将
middle.next
设置为null时,节点的链接断开,链接列表分为两半,其中left_head
和right_head
指向相应的左右段。
right_head
was set before middle.next
became null. right_head
之前设置middle.next
成为空。 So it holds the value of whatever was set before it becomes null. 因此,它保留在变为null之前设置的所有值。
You did not post the entire code segment, so I cannot confirm with certainty, but given merge sort
's desire to split the array into two pieces, sort them, and then combine them, it probably will reselect the middle
element to which it should sort around for the next go, which is why it resets after this one. 您没有发布整个代码段,所以我无法确定,但是由于
merge sort
希望将数组分为两部分,对它们进行排序,然后将它们组合在一起,所以它可能会重新选择应该将其作为middle
元素进行下一步操作,这就是为什么在此操作之后会重置的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.