问题
There is a linked list that needs to be sorted in O(n Log n)
time.
I would like to use merge sort, but I can't figure out how to implement it by extending the SplDoublyLinkedList
class.
The main problem I encountered is that I cannot divide the SplDoublyLinkedList
in half without allocating additional memory.
If I had independent nodes, I could easily set pointer "next" of the node to a null value, but SplDoublyLinkedList
doesn't let me do it.
I mean something like that in Java:
node mergeSort(node h)
{
if (h == null || h.next == null) {
return h;
}
node middle = getMiddle(h);
node nextOfMiddle = middle.next;
middle.next = null;
node left = mergeSort(h);
node right = mergeSort(nextofmiddle);
node sortedlist = sortedMerge(left, right);
return sortedlist;
}
Should I really use SplDoublyLinkedList
class in that case, or do I need to write my own linked list implementation?
来源:https://stackoverflow.com/questions/56432213/how-to-sort-spldoublylinkedlist