<p>I was recently brushing up on some fundamentals and found merge sorting a linked list to be a pretty good challenge. If you have a good implementation then show it off here.</p>

[{'answer_id': 7802, 'author': 'John with waffle', 'author_id': 279, 'author_profile': 'https://Stackoverflow.com/users/279', 'pm_score': 3, 'selected': False, 'text': '<p>One interesting way is to maintain a stack, and only merge if the list on the stack has the same number of elements, and otherwise push the list, until you run out of elements in the incoming list, and then merge up the stack.</p>\n'}, {'answer_id': 43395, 'author': 'paperhorse', 'author_id': 4498, 'author_profile': 'https://Stackoverflow.com/users/4498', 'pm_score': 2, 'selected': False, 'text': '<p>The simplest is from \n<a href="http://www.dcc.uchile.cl/~rbaeza/handbook/algs/4/421.sort.p.html" rel="nofollow noreferrer">Gonnet + Baeza Yates Handbook of Algorithms</a>. You call it with the number of sorted elements you want, which recursively gets bisected until it reaches a request for a size one list which you then just peel off the front of the original list. These all get merged up into a full sized sorted list.<p>\n[Note that the cool stack-based one in the first post is called the Online Mergesort and it gets the tiniest mention in an exercise in Knuth Vol 3]</p>\n'}, {'answer_id': 3032462, 'author': 'Dave Gamble', 'author_id': 133758, 'author_profile': 'https://Stackoverflow.com/users/133758', 'pm_score': 3, 'selected': False, 'text': '\n\n<p>Heavily based on the EXCELLENT code from: <a href="http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html" rel="noreferrer">http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html</a></p>\n\n<p>Trimmed slightly, and tidied:</p>\n\n<pre class="lang-c prettyprint-override"><code>\ntypedef struct _aList {\n    struct _aList* next;\n    struct _aList* prev; // Optional.\n       // some data\n} aList;\n\naList *merge_sort_list(aList *list,int (*compare)(aList *one,aList *two))\n{\n    int listSize=1,numMerges,leftSize,rightSize;\n    aList *tail,*left,*right,*next;\n    if (!list || !list->next) return list;  // Trivial case\n\n    do { // For each power of two&lt;=list length\n        numMerges=0,left=list;tail=list=0; // Start at the start\n\n        while (left) { // Do this list_len/listSize times:\n            numMerges++,right=left,leftSize=0,rightSize=listSize;\n            // Cut list into two halves (but don\'t overrun)\n            while (right && leftSize&lt;listSize) leftSize++,right=right->next;\n            // Run through the lists appending onto what we have so far.\n            while (leftSize&gt;0 || (rightSize&gt;0 && right)) {\n                // Left empty, take right OR Right empty, take left, OR compare.\n                if (!leftSize)                  {next=right;right=right->next;rightSize--;}\n                else if (!rightSize || !right)  {next=left;left=left->next;leftSize--;}\n                else if (compare(left,right)&lt;0) {next=left;left=left->next;leftSize--;}\n                else                            {next=right;right=right->next;rightSize--;}\n                // Update pointers to keep track of where we are:\n                if (tail) tail->next=next;  else list=next;\n                // Sort prev pointer\n                next->prev=tail; // Optional.\n                tail=next;          \n            }\n            // Right is now AFTER the list we just sorted, so start the next sort there.\n            left=right;\n        }\n        // Terminate the list, double the list-sort size.\n        tail->next=0,listSize&lt;&lt;=1;\n    } while (numMerges&gt;1); // If we only did one merge, then we just sorted the whole list.\n    return list;\n}\n\n</code></pre>\n\n<p>NB: This is O(NLog(N)) guaranteed, and uses O(1) resources (no recursion, no stack, nothing).</p>\n'}, {'answer_id': 3032553, 'author': 'Dave Gamble', 'author_id': 133758, 'author_profile': 'https://Stackoverflow.com/users/133758', 'pm_score': 4, 'selected': False, 'text': '\n\n<p>A simpler/clearer implementation might be the recursive implementation, from which the NLog(N) execution time is more clear.</p>\n\n<pre class="lang-c prettyprint-override"><code>typedef struct _aList {\n    struct _aList* next;\n    struct _aList* prev; // Optional.\n    // some data\n} aList;\n\naList* merge_sort_list_recursive(aList *list,int (*compare)(aList *one,aList *two))\n{\n    // Trivial case.\n    if (!list || !list-&gt;next)\n        return list;\n\n    aList *right = list,\n          *temp  = list,\n          *last  = list,\n          *result = 0,\n          *next   = 0,\n          *tail   = 0;\n\n    // Find halfway through the list (by running two pointers, one at twice the speed of the other).\n    while (temp &amp;&amp; temp-&gt;next)\n    {\n        last = right;\n        right = right-&gt;next;\n        temp = temp-&gt;next-&gt;next;\n    }\n\n    // Break the list in two. (prev pointers are broken here, but we fix later)\n    last-&gt;next = 0;\n\n    // Recurse on the two smaller lists:\n    list = merge_sort_list_recursive(list, compare);\n    right = merge_sort_list_recursive(right, compare);\n\n    // Merge:\n    while (list || right)\n    {\n        // Take from empty lists, or compare:\n        if (!right) {\n            next = list;\n            list = list-&gt;next;\n        } else if (!list) {\n            next = right;\n            right = right-&gt;next;\n        } else if (compare(list, right) &lt; 0) {\n            next = list;\n            list = list-&gt;next;\n        } else {\n            next = right;\n            right = right-&gt;next;\n        }\n        if (!result) {\n            result=next;\n        } else {\n            tail-&gt;next=next;\n        }\n        next-&gt;prev = tail;  // Optional.\n        tail = next;\n    }\n    return result;\n}\n</code></pre>\n\n<p>NB: This has a Log(N) storage requirement for the recursion. Performance should be roughly comparable with the other strategy I posted. There is a potential optimisation here by running the merge loop while (list &amp;&amp; right), and simple appending the remaining list (since we don\'t really care about the end of the lists; knowing that they\'re merged suffices).</p>\n'}, {'answer_id': 6608434, 'author': 'Pramod', 'author_id': 833228, 'author_profile': 'https://Stackoverflow.com/users/833228', 'pm_score': -1, 'selected': False, 'text': '\n\n<pre class="lang-java prettyprint-override"><code>public int[] msort(int[] a) {\n    if (a.Length &gt; 1) {\n        int min = a.Length / 2;\n        int max = min;\n\n        int[] b = new int[min];\n        int[] c = new int[max]; // dividing main array into two half arrays\n        for (int i = 0; i &lt; min; i++) {\n            b[i] = a[i];\n        }\n\n        for (int i = min; i &lt; min + max; i++) {\n            c[i - min] = a[i];\n        }\n\n        b = msort(b);\n        c = msort(c);\n\n        int x = 0;\n        int y = 0;\n        int z = 0;\n\n        while (b.Length != y &amp;&amp; c.Length != z) {\n            if (b[y] &lt; c[z]) {\n                a[x] = b[y];\n                //r--\n                x++;\n                y++;\n            } else {\n                a[x] = c[z];\n                x++;\n                z++;\n            }\n        }\n\n        while (b.Length != y) {\n            a[x] = b[y];\n            x++;\n            y++;\n        }\n\n        while (c.Length != z) {\n            a[x] = c[z];\n            x++;\n            z++;\n        }\n    }\n\n    return a;\n}\n</code></pre>\n'}, {'answer_id': 8238253, 'author': 'jayadev', 'author_id': 302987, 'author_profile': 'https://Stackoverflow.com/users/302987', 'pm_score': 6, 'selected': False, 'text': '\n<p>Wonder why it should be big challenge as it is stated here, here is a straightforward implementation in Java with out any &quot;clever tricks&quot;.</p>\n<pre class="lang-java prettyprint-override"><code>//The main function\npublic static Node merge_sort(Node head) \n{\n    if(head == null || head.next == null) \n        return head;\n        \n    Node middle = getMiddle(head);      //get the middle of the list\n    Node left_head = head;\n    Node right_head = middle.next; \n    middle.next = null;             //split the list into two halfs\n\n    return merge(merge_sort(left_head), merge_sort(right_head));  //recurse on that\n}\n\n//Merge subroutine to merge two sorted lists\npublic static Node merge(Node a, Node b)\n{\n    Node dummyHead = new Node();\n    for(Node current  = dummyHead; a != null &amp;&amp; b != null; current = current.next;)\n    {\n        if(a.data &lt;= b.data) \n        {\n            current.next = a; \n            a = a.next; \n        }\n        else\n        { \n            current.next = b;\n            b = b.next; \n        }\n        \n    }\n    dummyHead.next = (a == null) ? b : a;\n    return dummyHead.next;\n}\n\n//Finding the middle element of the list for splitting\npublic static Node getMiddle(Node head)\n{\n    if(head == null) \n        return head;\n    \n    Node slow = head, fast = head;\n    \n    while(fast.next != null &amp;&amp; fast.next.next != null)\n    {\n        slow = slow.next;\n        fast = fast.next.next;\n    }\n    return slow;\n}\n</code></pre>\n'}, {'answer_id': 11486661, 'author': 'Ed Wynn', 'author_id': 1525946, 'author_profile': 'https://Stackoverflow.com/users/1525946', 'pm_score': 1, 'selected': False, 'text': '\n\n<p>Here is my implementation of Knuth\'s "List merge sort" (Algorithm 5.2.4L from Vol.3 of TAOCP, 2nd ed.).  I\'ll add some comments at the end, but here\'s a summary:</p>\n\n<p>On random input, it runs a bit faster than Simon Tatham\'s code (see Dave Gamble\'s non-recursive answer, with a link) but a bit slower than Dave Gamble\'s recursive code.  It\'s harder to understand than either.  At least in my implementation, it requires each element to have TWO pointers to elements.  (An alternative would be one pointer and a boolean flag.)  So, it\'s probably not a useful approach.  However, one distinctive point is that it runs very fast if the input has long stretches that are already sorted.</p>\n\n<pre class="lang-c prettyprint-override"><code>element *knuthsort(element *list)\n{ /* This is my attempt at implementing Knuth\'s Algorithm 5.2.4L "List merge sort"\n     from Vol.3 of TAOCP, 2nd ed. */\n  element *p, *pnext, *q, *qnext, head1, head2, *s, *t;\n  if(!list) return NULL;\n\nL1: /* This is the clever L1 from exercise 12, p.167, solution p.647. */\n  head1.next=list;\n  t=&amp;head2;\n  for(p=list, pnext=p-&gt;next; pnext; p=pnext, pnext=p-&gt;next) {\n    if( cmp(p,pnext) &gt; 0 ) { t-&gt;next=NULL; t-&gt;spare=pnext; t=p; }\n  }\n  t-&gt;next=NULL; t-&gt;spare=NULL; p-&gt;spare=NULL;\n  head2.next=head2.spare;\n\nL2: /* begin a new pass: */\n  t=&amp;head2;\n  q=t-&gt;next;\n  if(!q) return head1.next;\n  s=&amp;head1;\n  p=s-&gt;next;\n\nL3: /* compare: */\n  if( cmp(p,q) &gt; 0 ) goto L6;\nL4: /* add p onto the current end, s: */\n  if(s-&gt;next) s-&gt;next=p; else s-&gt;spare=p;\n  s=p;\n  if(p-&gt;next) { p=p-&gt;next; goto L3; } \n  else p=p-&gt;spare;\nL5: /* complete the sublist by adding q and all its successors: */\n  s-&gt;next=q; s=t;\n  for(qnext=q-&gt;next; qnext; q=qnext, qnext=q-&gt;next);\n  t=q; q=q-&gt;spare;\n  goto L8;\nL6: /* add q onto the current end, s: */\n  if(s-&gt;next) s-&gt;next=q; else s-&gt;spare=q;\n  s=q;\n  if(q-&gt;next) { q=q-&gt;next; goto L3; } \n  else q=q-&gt;spare;\nL7: /* complete the sublist by adding p and all its successors: */\n  s-&gt;next=p;\n  s=t;\n  for(pnext=p-&gt;next; pnext; p=pnext, pnext=p-&gt;next);\n  t=p; p=p-&gt;spare;\nL8: /* is this end of the pass? */\n  if(q) goto L3;\n  if(s-&gt;next) s-&gt;next=p; else s-&gt;spare=p;\n  t-&gt;next=NULL; t-&gt;spare=NULL;\n  goto L2;\n}\n</code></pre>\n'}, {'answer_id': 11491064, 'author': 'Ed Wynn', 'author_id': 1525946, 'author_profile': 'https://Stackoverflow.com/users/1525946', 'pm_score': 2, 'selected': False, 'text': "<p>Here's an alternative recursive version.  This does not need to step along the list to split it: we supply a pointer to a head element (which is not part of the sort) and a length, and the recursive function returns a pointer to the end of the sorted list. </p>\n\n<pre><code>element* mergesort(element *head,long lengtho)\n{ \n  long count1=(lengtho/2), count2=(lengtho-count1);\n  element *next1,*next2,*tail1,*tail2,*tail;\n  if (lengtho&lt;=1) return head-&gt;next;  /* Trivial case. */\n\n  tail1 = mergesort(head,count1);\n  tail2 = mergesort(tail1,count2);\n  tail=head;\n  next1 = head-&gt;next;\n  next2 = tail1-&gt;next;\n  tail1-&gt;next = tail2-&gt;next; /* in case this ends up as the tail */\n  while (1) {\n    if(cmp(next1,next2)&lt;=0) {\n      tail-&gt;next=next1; tail=next1;\n      if(--count1==0) { tail-&gt;next=next2; return tail2; }\n      next1=next1-&gt;next;\n    } else {\n      tail-&gt;next=next2; tail=next2;\n      if(--count2==0) { tail-&gt;next=next1; return tail1; }\n      next2=next2-&gt;next;\n    }\n  }\n}\n</code></pre>\n"}, {'answer_id': 18246901, 'author': 'Hari', 'author_id': 216562, 'author_profile': 'https://Stackoverflow.com/users/216562', 'pm_score': 1, 'selected': False, 'text': '<p>There\'s a non-recursive linked-list mergesort in <a href="https://raw.github.com/mono/mono/3baee55f958f6695d812ade649a407c2e920c19e/eglib/src/sort.frag.h" rel="nofollow">mono eglib</a>.</p>\n\n<p>The basic idea is that the control-loop for the various merges parallels the bitwise-increment of a binary integer.  There are <em>O(n)</em> merges to "insert" <em>n</em> nodes into the merge tree, and the rank of those merges corresponds to the binary digit that gets incremented.  Using this analogy, only <em>O(log n)</em> nodes of the merge-tree need to be materialized into a temporary holding array.</p>\n'}, {'answer_id': 27663998, 'author': 'Shital Shah', 'author_id': 207661, 'author_profile': 'https://Stackoverflow.com/users/207661', 'pm_score': 2, 'selected': False, 'text': '<p>I\'d been obsessing over optimizing clutter for this algorithm and below is what I\'ve finally arrived at. Lot of other code on Internet and StackOverflow is horribly bad. There are people trying to get middle point of the list, doing recursion, having multiple loops for left over nodes, maintaining counts of ton of things - ALL of which is unnecessary. MergeSort naturally fits to linked list and algorithm can be beautiful and compact but it\'s not trivial to get to that state.</p>\n\n<p>Below code maintains minimum number of variables and has minimum number of logical steps needed for the algorithm (i.e. without making code unmaintainable/unreadable) as far as I know. However I haven\'t tried to minimize LOC and kept as much white space as necessary to keep things readable. I\'ve tested this code through fairly rigorous unit tests.</p>\n\n<p>Note that this answer combines few techniques from other answer <a href="https://stackoverflow.com/a/3032462/207661">https://stackoverflow.com/a/3032462/207661</a>. While the code is in C#, it should be trivial to convert in to C++, Java, etc.</p>\n\n<pre><code>SingleListNode&lt;T&gt; SortLinkedList&lt;T&gt;(SingleListNode&lt;T&gt; head) where T : IComparable&lt;T&gt;\n{\n    int blockSize = 1, blockCount;\n    do\n    {\n        //Maintain two lists pointing to two blocks, left and right\n        SingleListNode&lt;T&gt; left = head, right = head, tail = null;\n        head = null; //Start a new list\n        blockCount = 0;\n\n        //Walk through entire list in blocks of size blockCount\n        while (left != null)\n        {\n            blockCount++;\n\n            //Advance right to start of next block, measure size of left list while doing so\n            int leftSize = 0, rightSize = blockSize;\n            for (;leftSize &lt; blockSize &amp;&amp; right != null; ++leftSize)\n                right = right.Next;\n\n            //Merge two list until their individual ends\n            bool leftEmpty = leftSize == 0, rightEmpty = rightSize == 0 || right == null;\n            while (!leftEmpty || !rightEmpty)\n            {\n                SingleListNode&lt;T&gt; smaller;\n                //Using &lt;= instead of &lt; gives us sort stability\n                if (rightEmpty || (!leftEmpty &amp;&amp; left.Value.CompareTo(right.Value) &lt;= 0))\n                {\n                    smaller = left; left = left.Next; --leftSize;\n                    leftEmpty = leftSize == 0;\n                }\n                else\n                {\n                    smaller = right; right = right.Next; --rightSize;\n                    rightEmpty = rightSize == 0 || right == null;\n                }\n\n                //Update new list\n                if (tail != null)\n                    tail.Next = smaller;\n                else\n                    head = smaller;\n                tail = smaller;\n            }\n\n            //right now points to next block for left\n            left = right;\n        }\n\n        //terminate new list, take care of case when input list is null\n        if (tail != null)\n            tail.Next = null;\n\n        //Lg n iterations\n        blockSize &lt;&lt;= 1;\n\n    } while (blockCount &gt; 1);\n\n    return head;\n}\n</code></pre>\n\n<p><strong>Points of interest</strong></p>\n\n<ul>\n<li>There is no special handling for cases like null list of list of 1 etc required. These cases "just works".</li>\n<li>Lot of "standard" algorithms texts have two loops to go over leftover elements to handle the case when one list is shorter than other. Above code eliminates need for it.</li>\n<li>We make sure sort is stable</li>\n<li>The inner while loop which is a hot spot evaluates 3 expressions per iteration on average which I think is minimum one can do.</li>\n</ul>\n\n<p>Update: @ideasman42 has <a href="https://gist.github.com/ideasman42/5921b0edfc6aa41a9ce0" rel="nofollow noreferrer">translated above code to C/C++</a> along with suggestions for fixing comments and bit more improvement. Above code is now up to date with these.</p>\n'}, {'answer_id': 33899907, 'author': 'Jon Meyer', 'author_id': 5600008, 'author_profile': 'https://Stackoverflow.com/users/5600008', 'pm_score': 2, 'selected': False, 'text': '<p>I decided to test the examples here, and also one more approach, originally written by Jonathan Cunningham in Pop-11. I coded all the approaches in C# and did a comparison with a range of different list sizes. I compared the Mono eglib approach by Raja R Harinath, the C# code by Shital Shah, the Java approach by Jayadev, the recursive and non-recursive versions by David Gamble, the first C code by Ed Wynn (this crashed with my sample dataset, I didn\'t debug), and Cunningham\'s version. Full code here: <a href="https://gist.github.com/314e572808f29adb0e41.git" rel="nofollow noreferrer">https://gist.github.com/314e572808f29adb0e41.git</a>.</p>\n<p>Mono eglib is based on a similar idea to Cunningham\'s and is of comparable speed, unless the list happens to be sorted already, in which case Cunningham\'s approach is much much faster (if its partially sorted, the eglib is slightly faster). The eglib code uses a fixed table to hold the merge sort recursion, whereas Cunningham\'s approach works by using increasing levels of recursion - so it starts out using no recursion, then 1-deep recursion, then 2-deep recursion and so on, according to how many steps are needed to do the sort. I find the Cunningham code a little easier to follow and there is no guessing involved in how big to make the recursion table, so it gets my vote. The other approaches I tried from this page were two or more times slower.</p>\n<p>Here is the C# port of the Pop-11 sort:</p>\n<pre class="lang-cs prettyprint-override"><code>/// &lt;summary&gt;\n/// Sort a linked list in place. Returns the sorted list.\n/// Originally by Jonathan Cunningham in Pop-11, May 1981.\n/// Ported to C# by Jon Meyer.\n/// &lt;/summary&gt;\npublic class ListSorter&lt;T&gt; where T : IComparable&lt;T&gt; {\n    SingleListNode&lt;T&gt; workNode = new SingleListNode&lt;T&gt;(default(T));\n    SingleListNode&lt;T&gt; list;\n\n    /// &lt;summary&gt;\n    /// Sorts a linked list. Returns the sorted list.\n    /// &lt;/summary&gt;\n    public SingleListNode&lt;T&gt; Sort(SingleListNode&lt;T&gt; head) {\n        if (head == null) throw new NullReferenceException(&quot;head&quot;);\n        list = head;\n\n        var run = GetRun(); // get first run\n        // As we progress, we increase the recursion depth. \n        var n = 1;\n        while (list != null) {\n            var run2 = GetSequence(n);\n            run = Merge(run, run2);\n            n++;\n        }\n        return run;\n    }\n\n    // Get the longest run of ordered elements from list.\n    // The run is returned, and list is updated to point to the\n    // first out-of-order element.\n    SingleListNode&lt;T&gt; GetRun() {\n        var run = list; // the return result is the original list\n        var prevNode = list;\n        var prevItem = list.Value;\n\n        list = list.Next; // advance to the next item\n        while (list != null) {\n            var comp = prevItem.CompareTo(list.Value);\n            if (comp &gt; 0) {\n                // reached end of sequence\n                prevNode.Next = null;\n                break;\n            }\n            prevItem = list.Value;\n            prevNode = list;\n            list = list.Next;\n        }\n        return run;\n    }\n\n    // Generates a sequence of Merge and GetRun() operations.\n    // If n is 1, returns GetRun()\n    // If n is 2, returns Merge(GetRun(), GetRun())\n    // If n is 3, returns Merge(Merge(GetRun(), GetRun()),\n    //                          Merge(GetRun(), GetRun()))\n    // and so on.\n    SingleListNode&lt;T&gt; GetSequence(int n) {\n        if (n &lt; 2) {\n            return GetRun();\n        } else {\n            n--;\n            var run1 = GetSequence(n);\n            if (list == null) return run1;\n            var run2 = GetSequence(n);\n            return Merge(run1, run2);\n        }\n    }\n\n    // Given two ordered lists this returns a list that is the\n    // result of merging the two lists in-place (modifying the pairs\n    // in list1 and list2).\n    SingleListNode&lt;T&gt; Merge(SingleListNode&lt;T&gt; list1, SingleListNode&lt;T&gt; list2) {\n        // we reuse a single work node to hold the result.\n        // Simplifies the number of test cases in the code below.\n        var prevNode = workNode;\n        while (true) {\n            if (list1.Value.CompareTo(list2.Value) &lt;= 0) {\n                // list1 goes first\n                prevNode.Next = list1;\n                prevNode = list1;\n                if ((list1 = list1.Next) == null) {\n                    // reached end of list1 - join list2 to prevNode\n                    prevNode.Next = list2;\n                    break;\n                }\n            } else {        // same but for list2\n                prevNode.Next = list2;\n                prevNode = list2;\n                if ((list2 = list2.Next) == null) {\n                    prevNode.Next = list1;\n                    break;\n                }\n            }\n        }\n\n        // the result is in the back of the workNode\n        return workNode.Next;\n    }\n}\n</code></pre>\n'}, {'answer_id': 33987943, 'author': 'rcgldr', 'author_id': 3282056, 'author_profile': 'https://Stackoverflow.com/users/3282056', 'pm_score': 1, 'selected': False, 'text': '<p>Another example of a non-recursive merge sort for linked lists, where the functions are not part of a class. This example code and HP / Microsoft <code>std::list::sort</code> both use the same basic algorithm. A bottom up, non-recursive, merge sort that uses a small (26 to 32) array of pointers to the first nodes of a list, where <code>array[i]</code> is either 0 or points to a list of size 2 to the power i. On my system, Intel 2600K 3.4ghz, it can sort 4 million nodes with 32 bit unsigned integers as data in about 1 second.</p>\n<pre class="lang-c prettyprint-override"><code>typedef struct NODE_{\n    struct NODE_ * next;\n    uint32_t data;\n}NODE;\n\nNODE * MergeLists(NODE *, NODE *); /* prototype */\n\n/* sort a list using array of pointers to list       */\n/* aList[i] == NULL or ptr to list with 2^i nodes    */\n \n#define NUMLISTS 32             /* number of lists */\nNODE * SortList(NODE *pList)\n{\nNODE * aList[NUMLISTS];         /* array of lists */\nNODE * pNode;\nNODE * pNext;\nint i;\n    if(pList == NULL)           /* check for empty list */\n        return NULL;\n    for(i = 0; i &lt; NUMLISTS; i++)   /* init array */\n        aList[i] = NULL;\n    pNode = pList;              /* merge nodes into array */\n    while(pNode != NULL){\n        pNext = pNode-&gt;next;\n        pNode-&gt;next = NULL;\n        for(i = 0; (i &lt; NUMLISTS) &amp;&amp; (aList[i] != NULL); i++){\n            pNode = MergeLists(aList[i], pNode);\n            aList[i] = NULL;\n        }\n        if(i == NUMLISTS)   /* don\'t go beyond end of array */\n            i--;\n        aList[i] = pNode;\n        pNode = pNext;\n    }\n    pNode = NULL;           /* merge array into one list */\n    for(i = 0; i &lt; NUMLISTS; i++)\n        pNode = MergeLists(aList[i], pNode);\n    return pNode;\n}\n\n/* merge two already sorted lists                    */\n/* compare uses pSrc2 &lt; pSrc1 to follow the STL rule */\n/*   of only using &lt; and not &lt;=                      */\nNODE * MergeLists(NODE *pSrc1, NODE *pSrc2)\n{\nNODE *pDst = NULL;          /* destination head ptr */\nNODE **ppDst = &amp;pDst;       /* ptr to head or prev-&gt;next */\n    if(pSrc1 == NULL)\n        return pSrc2;\n    if(pSrc2 == NULL)\n        return pSrc1;\n    while(1){\n        if(pSrc2-&gt;data &lt; pSrc1-&gt;data){  /* if src2 &lt; src1 */\n            *ppDst = pSrc2;\n            pSrc2 = *(ppDst = &amp;(pSrc2-&gt;next));\n            if(pSrc2 == NULL){\n                *ppDst = pSrc1;\n                break;\n            }\n        } else {                        /* src1 &lt;= src2 */\n            *ppDst = pSrc1;\n            pSrc1 = *(ppDst = &amp;(pSrc1-&gt;next));\n            if(pSrc1 == NULL){\n                *ppDst = pSrc2;\n                break;\n            }\n        }\n    }\n    return pDst;\n}\n</code></pre>\n<hr />\n<p>Visual Studio 2015 changed <code>std::list::sort</code> to be based on iterators instead of lists, and also changed to a top down merge sort, which requires the overhead of scanning. I initially assumed that the switch to top down was needed to work with the iterators, but when it was asked about again, I investigated this and determined that the switch to the slower top down method was not needed, and bottom up could be implemented using the same iterator based logic. The answer in this link explains this and provide a stand-alone example as well as a replacement for VS2019\'s <code>std::list::sort()</code> in the include file &quot;list&quot;.</p>\n<p><a href="https://stackoverflow.com/questions/40622430/stdlistsort-why-the-sudden-switch-to-top-down-strategy/40629882#40629882">`std::list&lt;&gt;::sort()` - why the sudden switch to top-down strategy?</a></p>\n'}, {'answer_id': 44095098, 'author': 'Vinayak Bansal', 'author_id': 5016535, 'author_profile': 'https://Stackoverflow.com/users/5016535', 'pm_score': 0, 'selected': False, 'text': '<p>This is the entire Piece of code which shows how we can create linklist in java and sort it using Merge sort. I am creating node in MergeNode class and there is another class MergesortLinklist where there is divide and merge logic.</p>\n\n<pre><code>class MergeNode {\n    Object value;\n    MergeNode next;\n\n    MergeNode(Object val) {\n        value = val;\n        next = null;\n\n    }\n\n    MergeNode() {\n        value = null;\n        next = null;\n\n    }\n\n    public Object getValue() {\n        return value;\n    }\n\n    public void setValue(Object value) {\n        this.value = value;\n    }\n\n    public MergeNode getNext() {\n        return next;\n    }\n\n    public void setNext(MergeNode next) {\n        this.next = next;\n    }\n\n    @Override\n    public String toString() {\n        return "MergeNode [value=" + value + ", next=" + next + "]";\n    }\n\n}\n\npublic class MergesortLinkList {\n    MergeNode head;\n    static int totalnode;\n\n    public MergeNode getHead() {\n        return head;\n    }\n\n    public void setHead(MergeNode head) {\n        this.head = head;\n    }\n\n    MergeNode add(int i) {\n        // TODO Auto-generated method stub\n        if (head == null) {\n            head = new MergeNode(i);\n            // System.out.println("head value is  "+head);\n            return head;\n\n        }\n        MergeNode temp = head;\n\n        while (temp.next != null) {\n            temp = temp.next;\n        }\n        temp.next = new MergeNode(i);\n        return head;\n\n    }\n\n    MergeNode mergesort(MergeNode nl1) {\n        // TODO Auto-generated method stub\n\n        if (nl1.next == null) {\n            return nl1;\n        }\n\n        int counter = 0;\n\n        MergeNode temp = nl1;\n\n        while (temp != null) {\n            counter++;\n            temp = temp.next;\n\n        }\n        System.out.println("total nodes  " + counter);\n\n        int middle = (counter - 1) / 2;\n\n        temp = nl1;\n        MergeNode left = nl1, right = nl1;\n        int leftindex = 0, rightindex = 0;\n\n        if (middle == leftindex) {\n            right = left.next;\n        }\n        while (leftindex &lt; middle) {\n\n            leftindex++;\n            left = left.next;\n            right = left.next;\n        }\n\n        left.next = null;\n        left = nl1;\n\n        System.out.println(left.toString());\n        System.out.println(right.toString());\n\n        MergeNode p1 = mergesort(left);\n        MergeNode p2 = mergesort(right);\n\n        MergeNode node = merge(p1, p2);\n\n        return node;\n\n    }\n\n    MergeNode merge(MergeNode p1, MergeNode p2) {\n        // TODO Auto-generated method stub\n\n        MergeNode L = p1;\n        MergeNode R = p2;\n\n        int Lcount = 0, Rcount = 0;\n\n        MergeNode tempnode = null;\n\n        while (L != null &amp;&amp; R != null) {\n\n            int val1 = (int) L.value;\n\n            int val2 = (int) R.value;\n\n            if (val1 &gt; val2) {\n\n                if (tempnode == null) {\n                    tempnode = new MergeNode(val2);\n                    R = R.next;\n                } else {\n\n                    MergeNode store = tempnode;\n\n                    while (store.next != null) {\n                        store = store.next;\n                    }\n                    store.next = new MergeNode(val2);\n\n                    R = R.next;\n                }\n\n            } else {\n                if (tempnode == null) {\n                    tempnode = new MergeNode(val1);\n                    L = L.next;\n                } else {\n\n                    MergeNode store = tempnode;\n\n                    while (store.next != null) {\n                        store = store.next;\n                    }\n                    store.next = new MergeNode(val1);\n\n                    L = L.next;\n                }\n\n            }\n\n        }\n\n        MergeNode handle = tempnode;\n\n        while (L != null) {\n\n            while (handle.next != null) {\n\n                handle = handle.next;\n\n            }\n            handle.next = L;\n\n            L = null;\n\n        }\n\n        // Copy remaining elements of L[] if any\n        while (R != null) {\n            while (handle.next != null) {\n\n                handle = handle.next;\n\n            }\n            handle.next = R;\n\n            R = null;\n\n        }\n\n        System.out.println("----------------sorted value-----------");\n        System.out.println(tempnode.toString());\n        return tempnode;\n    }\n\n    public static void main(String[] args) {\n        MergesortLinkList objsort = new MergesortLinkList();\n        MergeNode n1 = objsort.add(9);\n        MergeNode n2 = objsort.add(7);\n        MergeNode n3 = objsort.add(6);\n        MergeNode n4 = objsort.add(87);\n        MergeNode n5 = objsort.add(16);\n        MergeNode n6 = objsort.add(81);\n\n        MergeNode n7 = objsort.add(21);\n        MergeNode n8 = objsort.add(16);\n\n        MergeNode n9 = objsort.add(99);\n        MergeNode n10 = objsort.add(31);\n\n        MergeNode val = objsort.mergesort(n1);\n\n        System.out.println("===============sorted values=====================");\n        while (val != null) {\n            System.out.println(" value is  " + val.value);\n            val = val.next;\n        }\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 51832084, 'author': 'Testing123', 'author_id': 3021645, 'author_profile': 'https://Stackoverflow.com/users/3021645', 'pm_score': 0, 'selected': False, 'text': "<p>I don't see any C++ solutions posted here. So, here it goes. Hope it helps someone. </p>\n\n<pre><code>class Solution {\npublic:\n    ListNode *merge(ListNode *left, ListNode *right){\n        ListNode *head = NULL, *temp = NULL;\n        // Find which one is the head node for the merged list\n        if(left-&gt;val &lt;= right-&gt;val){\n            head = left, temp = left;\n            left = left-&gt;next;\n        }\n        else{\n            head = right, temp = right;\n            right = right-&gt;next;\n        }\n        while(left &amp;&amp; right){\n            if(left-&gt;val &lt;= right-&gt;val){\n                temp-&gt;next = left;\n                temp = left;\n                left = left-&gt;next;\n            }\n            else{\n                temp-&gt;next = right;\n                temp = right;\n                right = right-&gt;next;\n            }\n        }\n        // If some elements still left in the left or the right list\n        if(left)\n            temp-&gt;next = left;\n        if(right)\n            temp-&gt;next = right;\n        return head;\n    }\n\n    ListNode* sortList(ListNode* head){\n        if(!head || !head-&gt;next)\n            return head;\n\n        // Find the length of the list\n        int length = 0;\n        ListNode *temp = head;\n        while(temp){\n            length++;\n            temp = temp-&gt;next;\n        }\n        // Reset temp\n        temp = head;\n        // Store half of it in left and the other half in right\n        // Create two lists and sort them\n        ListNode *left = temp, *prev = NULL;\n        int i = 0, mid = length / 2;\n        // Left list\n        while(i &lt; mid){\n            prev = temp;\n            temp = temp-&gt;next;\n            i++;\n        }\n        // The end of the left list should point to NULL\n        if(prev)\n            prev-&gt;next = NULL;\n        // Right list\n        ListNode  *right = temp;\n        // Sort left list\n        ListNode *sortedLeft = sortList(left);\n        // Sort right list\n        ListNode *sortedRight = sortList(right);\n        // Merge them\n        ListNode *sortedList = merge(sortedLeft, sortedRight);\n        return sortedList;\n    }\n};\n</code></pre>\n"}, {'answer_id': 53996320, 'author': 'Pratik Patil', 'author_id': 4773290, 'author_profile': 'https://Stackoverflow.com/users/4773290', 'pm_score': 0, 'selected': False, 'text': '<p>Here is the Java Implementation of Merge Sort on Linked List:</p>\n\n<blockquote>\n  <ul>\n  <li>Time Complexity: O(n.logn)</li>\n  <li>Space Complexity: O(1) - Merge sort implementation on Linked List avoids the O(n) auxiliary storage cost normally associated with the\n  algorithm</li>\n  </ul>\n</blockquote>\n\n<pre><code>class Solution\n{\n    public ListNode mergeSortList(ListNode head) \n    {\n        if(head == null || head.next == null)\n            return head;\n\n        ListNode mid = getMid(head), second_head = mid.next; mid.next = null;\n\n        return merge(mergeSortList(head), mergeSortList(second_head));\n    }\n\n    private ListNode merge(ListNode head1, ListNode head2)\n    {\n        ListNode result = new ListNode(0), current = result;\n\n        while(head1 != null &amp;&amp; head2 != null)\n        {\n            if(head1.val &lt; head2.val)\n            {\n                current.next = head1;\n                head1 = head1.next;\n            }\n            else\n            {\n                current.next = head2;\n                head2 = head2.next;\n            }\n            current = current.next;\n        }\n\n        if(head1 != null) current.next = head1;\n        if(head2 != null) current.next = head2;\n\n        return result.next;\n    }\n\n    private ListNode getMid(ListNode head)\n    {\n        ListNode slow = head, fast = head.next;\n\n        while(fast != null &amp;&amp; fast.next != null)\n        {\n            slow = slow.next;\n            fast = fast.next.next;\n        }\n        return slow;\n    }\n}\n</code></pre>\n'}, {'answer_id': 54035854, 'author': 'Rick', 'author_id': 5983841, 'author_profile': 'https://Stackoverflow.com/users/5983841', 'pm_score': 1, 'selected': False, 'text': '<p>A tested, working <code>C++</code> version of single linked list, <strong>based on the highest voted answer</strong>.</p>\n\n<p><strong>singlelinkedlist.h:</strong></p>\n\n<pre class="lang-cpp prettyprint-override"><code>#pragma once\n#include &lt;stdexcept&gt;\n#include &lt;iostream&gt;\n#include &lt;initializer_list&gt;\nnamespace ythlearn{\n    template&lt;typename T&gt;\n    class Linkedlist{\n    public:\n        class Node{\n        public:\n            Node* next;\n            T elem;\n        };\n        Node head;\n        int _size;\n    public:\n        Linkedlist(){\n            head.next = nullptr;            \n            _size = 0;\n        }\n\n        Linkedlist(std::initializer_list&lt;T&gt; init_list){\n            head.next = nullptr;            \n            _size = 0;\n            for(auto s = init_list.begin(); s!=init_list.end(); s++){\n                push_left(*s);\n            }\n        }\n\n        int size(){\n            return _size;\n        }\n\n        bool isEmpty(){\n            return size() == 0;\n        }\n\n        bool isSorted(){\n            Node* n_ptr = head.next;\n            while(n_ptr-&gt;next != nullptr){\n                if(n_ptr-&gt;elem &gt; n_ptr-&gt;next-&gt;elem)\n                    return false;\n                n_ptr = n_ptr-&gt;next;\n            }\n            return true;\n        }\n\n        Linkedlist&amp; push_left(T elem){\n            Node* n = new Node;\n            n-&gt;elem = elem;\n            n-&gt;next = head.next;\n            head.next = n;\n            ++_size;\n            return *this;\n        }\n\n        void print(){\n                Node* loopPtr = head.next;\n                while(loopPtr != nullptr){\n                    std::cout &lt;&lt; loopPtr-&gt;elem &lt;&lt; " ";\n                    loopPtr = loopPtr-&gt;next;\n                }\n                std::cout &lt;&lt; std::endl;\n        }\n\n        void call_merge(){\n            head.next = merge_sort(head.next);\n        }\n\n        Node* merge_sort(Node* n){\n            if(n == nullptr || n-&gt;next == nullptr)\n                return n;\n            Node* middle = getMiddle(n);\n            Node* left_head = n;\n            Node* right_head = middle-&gt;next;\n            middle-&gt;next = nullptr;\n            return merge(merge_sort(left_head), merge_sort(right_head));\n        }\n\n        Node* getMiddle(Node* n){\n            if(n == nullptr)\n                return n;\n            Node* slow, *fast;\n            slow = fast = n;\n            while(fast-&gt;next != nullptr &amp;&amp; fast-&gt;next-&gt;next != nullptr){\n                slow = slow-&gt;next;\n                fast = fast-&gt;next-&gt;next;\n            }\n            return slow;\n        }\n\n        Node* merge(Node* a, Node* b){\n            Node dummyHead;\n            Node* current = &amp;dummyHead;\n            while(a != nullptr &amp;&amp; b != nullptr){\n                if(a-&gt;elem &lt; b-&gt;elem){\n                    current-&gt;next = a;\n                    a = a-&gt;next;\n                }else{\n                    current-&gt;next = b;\n                    b = b-&gt;next;\n                }\n                current = current-&gt;next;\n            }\n            current-&gt;next = (a == nullptr) ? b : a;\n            return dummyHead.next;\n        }\n\n        Linkedlist(const Linkedlist&amp;) = delete;\n        Linkedlist&amp; operator=(const Linkedlist&amp;) const = delete;\n        ~Linkedlist(){\n            Node* node_to_delete;\n            Node* ptr = head.next;\n            while(ptr != nullptr){\n                node_to_delete = ptr;\n                ptr = ptr-&gt;next;\n                delete node_to_delete;\n            }\n\n        }\n\n    };\n}\n</code></pre>\n\n<p><strong>main.cpp:</strong></p>\n\n<pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt;\n#include &lt;cassert&gt;\n#include "singlelinkedlist.h"\nusing namespace std;\nusing namespace ythlearn;\n\nint main(){\n    Linkedlist&lt;int&gt; l = {3,6,-5,222,495,-129,0};\n    l.print();\n    l.call_merge();\n    l.print();\n    assert(l.isSorted());\n    return 0;\n}\n</code></pre>\n'}, {'answer_id': 56240818, 'author': 'kundus', 'author_id': 11531469, 'author_profile': 'https://Stackoverflow.com/users/11531469', 'pm_score': 0, 'selected': False, 'text': "<p><strong>Simplest Java Implementation:</strong></p>\n\n<blockquote>\n  <p>Time Complexity: O(nLogn) n = number of nodes. Each iteration through the linked list doubles the size of the sorted smaller linked lists. For example, after the first iteration, the linked list will be sorted into two halves. After the second iteration, the linked list will be sorted into four halves. It will keep sorting up to the size of the linked list. This will take O(logn) doublings of the small linked lists' sizes to reach the original linked list size. The n in nlogn is there because each iteration of the linked list will take time proportional to the number of nodes in the originial linked list.</p>\n</blockquote>\n\n<pre><code>class Node {\n    int data;\n    Node next;\n    Node(int d) {\n        data = d;\n    }\n}\n\nclass LinkedList {\n    Node head;\n    public Node mergesort(Node head) {\n          if(head == null || head.next == null) return head;\n          Node middle = middle(head), middle_next = middle.next;\n          middle.next = null;\n          Node left = mergesort(head), right = mergesort(middle_next), node = merge(left, right);\n          return node;\n    } \n\n    public Node merge(Node first, Node second) {\n          Node node = null;\n          if (first == null) return second;\n          else if (second == null) return first;\n          else if (first.data &lt;= second.data) {\n              node = first;\n              node.next = merge(first.next, second);\n\n          } else {\n              node = second;\n              node.next = merge(first, second.next);\n          }\n          return node;\n    }\n\n    public Node middle(Node head) {\n          if (head == null) return head;\n          Node second = head, first = head.next;\n          while(first != null) {\n              first = first.next;\n              if (first != null) {\n                 second = second.next;\n                 first = first.next;\n              }\n          }\n          return second;\n    }\n\n}\n</code></pre>\n"}, {'answer_id': 59963477, 'author': 'kam', 'author_id': 7039094, 'author_profile': 'https://Stackoverflow.com/users/7039094', 'pm_score': 0, 'selected': False, 'text': "<p>Hey I know that this is a bit late an answer but got a fast simple one.</p>\n\n<p>The code is in F# but will goes in any language. Since this is an uncommen language of the ML family, I'll give some point to enhance the readability.\nF# are nesting done by tabulating. the last line of code in a function (nested part) are the return value. (x, y) is a tuple, x::xs is a list of the head x and tail xs (where xs can be empty), |> take the result of last line an pipe it as argument to the expression right of it (readability enhancing) and last (fun args -> some expression) are a lambda function.  </p>\n\n<pre><code>// split the list into a singleton list\nlet split list = List.map (fun x -&gt; [x]) lst\n\n// takes to list and merge them into a sorted list\nlet sort lst1 lst2 =\n   // nested function to hide accumulator\n   let rec s acc pair =\n       match pair with\n       // empty list case, return the sorted list\n       | [], [] -&gt; List.rev acc\n       | xs, [] | [], xs -&gt;\n          // one empty list case, \n          // append the rest of xs onto acc and return the sorted list\n          List.fold (fun ys y -&gt; y :: ys) acc xs\n          |&gt; List.rev\n       // general case\n       | x::xs, y::ys -&gt;\n          match x &lt; y with\n          | true -&gt; // cons x onto the accumulator\n              s (x::acc) (xs,y::ys)\n          | _ -&gt;\n              // cons y onto the accumulator\n              s (y::acc) (x::xs,ys)\n\n    s [] (lst1, lst2)  \n\nlet msort lst =\n  let rec merge acc lst =\n      match lst with\n      | [] -&gt;\n          match acc with\n          | [] -&gt; [] // empty list case\n          | _ -&gt; merge [] acc\n      | x :: [] -&gt; // single list case (x is a list)\n         match acc with\n         | [] -&gt; x // since acc are empty there are only x left, hence x are the sorted list.\n         | _ -&gt; merge [] (x::acc) // still need merging.\n       | x1 :: x2 :: xs -&gt;\n           // merge the lists x1 and x2 and add them to the acummulator. recursiv call\n           merge (sort x1 x2 :: acc) xs\n\n   // return part\n   split list // expand to singleton list list\n   |&gt; merge [] // merge and sort recursively.\n</code></pre>\n\n<p>It is important to notice that this is fully tail recursive so no possibility of stack overflow, and by first expanding the list to a singleton list list in one go we, lower the constant factor on the worst cost. Since merge are working on list of list, we can recursively merge and sort the inner list until we get to the fix point where all inner list are sorted into one list and then we return that list, hence collapsing from a list list to a list again.</p>\n"}, {'answer_id': 63142081, 'author': 'Merouane T.', 'author_id': 11200033, 'author_profile': 'https://Stackoverflow.com/users/11200033', 'pm_score': 0, 'selected': False, 'text': '<p>Here is the solution using <strong>Swift Programming Language</strong>.</p>\n<pre><code>//Main MergeSort Function\nfunc mergeSort(head: Node?) -&gt; Node? {\n   guard let head = head else { return nil }\n   guard let _ = head.next else { return head }\n\n   let middle = getMiddle(head: head)\n   let left = head\n   let right = middle.next\n\n   middle.next = nil\n\n   return merge(left: mergeSort(head: left), right: mergeSort(head: right))\n}\n\n//Merge Function\nfunc merge(left: Node?, right: Node?) -&gt; Node? {\n\n   guard let left = left, let right = right else { return nil}\n\n   let dummyHead: Node = Node(value: 0)\n\n   var current: Node? = dummyHead\n   var currentLeft: Node? = left\n   var currentRight: Node? = right\n\n   while currentLeft != nil &amp;&amp; currentRight != nil {\n       if currentLeft!.value &lt; currentRight!.value {\n        current?.next = currentLeft\n        currentLeft = currentLeft!.next\n       } else {\n        current?.next = currentRight\n        currentRight = currentRight!.next\n       }\n       current = current?.next\n   }\n\n\n   if currentLeft != nil {\n        current?.next = currentLeft\n   }\n\n   if currentRight != nil {\n        current?.next = currentRight\n   }\n\n   return dummyHead.next!\n}\n</code></pre>\n<p>And here are the <strong>Node Class</strong> &amp; <strong>getMiddle Method</strong></p>\n<pre><code>class Node { \n    //Node Class which takes Integers as value\n    var value: Int\n    var next: Node?\n    \n    init(value: Int) {\n        self.value = value\n    }\n}\n\nfunc getMiddle(head: Node) -&gt; Node {\n    guard let nextNode = head.next else { return head }\n    \n    var slow: Node = head\n    var fast: Node? = head\n    \n    while fast?.next?.next != nil {\n        slow = slow.next!\n        fast = fast!.next?.next\n    }\n    \n    \n    return slow\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/7685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/608/']