How to sort SplDoublyLinkedList?

你。 提交于 2019-12-11 14:58:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!