public static DLink SortedAdd(ref DLink pActive, DLink pNode) { // If the active list is empty if (pActive == null) { pActive = pNode; pNode.pPrev = null; pNode.pNext = null; } // If the active list is not empty else { // If the value of pNode is smaller than that of first node in active list // insert the node to the front in active list. if (pActive.DerivedCompareValue() > pNode.DerivedCompareValue()) { pNode.pNext = pActive; pNode.pPrev = null; pActive.pPrev = pNode; pActive = pNode; } // If the value of the pNode is bigger than that of first node, // it should find the right location in active list. else { DLink pCurr = pActive; while (pCurr.pNext != null) { if (pCurr.pNext.DerivedCompareValue() > pNode.DerivedCompareValue()) { break; } pCurr = pCurr.pNext; } pNode.pPrev = pCurr; pNode.pNext = pCurr.pNext; if (pCurr.pNext != null) { pCurr.pNext.pPrev = pNode; } pCurr.pNext = pNode; //pNode.pNext = pCurr.pNext; //pNode.pPrev = pCurr; //pCurr.pNext = pNode; } } return(pNode); }