Search code examples
javalinked-listmergesort

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:

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. But why right_head remains in place since it refers to middle.next which became null?

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.


Solution

  • 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.
    2) left head points to the first node in the left part of the split.
    3) right head points to the first node in the right part of the split, which is actually the next to the middle node.
    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.