currently I am learning about merge sort with Linked List. I don't understand well how to split the original ListNode in half.
I cannot understand clearly why ListNode left = mergeSort(head); isn't head entire original ListNode not only left half? and why method getMiddleNode only return slowptr?
as I assume, ListNode left = mergeSort(head); only contains left half but I want to understand how head is only become half.
Thank you!
Here is my code
class Solution {
public ListNode mergeSort(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode middle = getMiddleNode(head);
ListNode left = mergeSort(head);
ListNode right = mergeSort(middle);
return merge(left, right);
}
ListNode getMiddleNode(ListNode head)
{
ListNode pre = null;
ListNode slowptr = head;
ListNode fastptr = head;
while(fastptr != null || fastptr.next != null)
{
pre = slowptr;
slowptr = slowptr.next;
fastptr = fastptr.next.next;
}
pre.next = null;
return slowptr;
}
}