// Delete the mininum node, and return it. This is where the log n // magic happens. Pairs the sub-list together, then sweeps up the pairs // into one tree again. public T deleteMin() { if (isEmpty()) { return(default(T)); } // NOTE: the final_cast is needed so the user can modify his own data. T ret = top.getNode(); HeapNode <T> newtop, i, j; if (top.getChild() == null) // Only one element in heap { top = null; size--; return(ret); } // First of two passes: combine pairs of roots together, from // left to right. i = top.getChild(); // Note, end condition is too complicated for more generalized loops while (true) { // i is the first, j is the second if ((j = i.getNext()) == null) // If i is the odd man out (no partner j) { break; } if (i == merge(i, j)) // i came out on top { if (i.getNext() == null) // i is now the last in the loop { break; } i = i.getNext(); } else // j came out on top { if (j.getNext() == null) // j is the last in the loop { i = j; // As a set up for the next pass break; } i = j.getNext(); } } // Iterate the other way, combining each new tree with the rightmost newtop = i; j = i.getPrev(); while (j != null) { newtop = merge(newtop, j); j = newtop.getPrev(); } top = newtop; size--; return(ret); }