插入排序的具体方法在上文已经介绍过,此文不再赘述。
对于数组,可以使用索引来轻易操作上下元素,但是单链表则只能通过指向下一节点的元素来操作。
因此,需要两个指针firstOutOfOrder(指向第一个无序元素的节点)和lastInOrder(指向最后一个有序元素的节点)。
首先,比较firstOutOfOrder->data和第一个节点的data。如果firstOutOfOrder>data<first->data那么把firstOutOfOrder节点放在第一个。否则,从第二个节点开始找firstOutOfOrder要插入的位置。使用两个指针,current和trailCurrent来查找链表。trailCurrent指向current之前的那个节点。其中需要考虑一些特殊情况,空链表,只有一个节点的链表或者节点firstOutOfOrder在正确的位置上。
void insertSort()
{
if(firstOutOfOrder->data<first->data)
{
move firstOutOfOrder before first;
}
else
{
trailCurrent = first;
current = first->next;
while(current->data<firstOutOfOrder->data)
{
trailCurrent =trailCurrent->next;
current = current->next;
}
if(current!= firstOutOfOrder)