我正在尝试对链表进行排序,但不知何故,在交换节点期间,它会进入循环。
我不允许交换值,而是交换指针。有人可以看看,告诉我可能出错的地方:
for (IntNode *index = head; index != 0; index = index->next)
{
for (IntNode *selection = head; selection != 0; selection = selection->next)
{
if (index->data > selection->data && order == 1)
{
IntNode *prev1 = new IntNode;
IntNode *after1= new IntNode;
IntNode *prev2= new IntNode;
IntNode *after2= new IntNode;
prev1->next = NULL;
prev2->next = NULL;
after1->next = NULL;
after2->next = NULL;
for (IntNode *index1 = head; index1 != 0; index1 = index1->next)
{
if(index1->next == index)
{
prev1 = index1;
after1->next = index1->next->next;
}
if(index1->next == selection)
{
prev2 = index1;
after2->next = index1->next->next;
}
}
// now swap
IntNode *tempPrev= new IntNode;
IntNode *tempAfter= new IntNode;
tempPrev->next = NULL;
tempAfter->next = NULL;
tempPrev->next = prev1->next;
tempAfter->next = after1->next;
prev1->next = selection;
selection->next = after1;
prev2->next = tempPrev->next;
index->next = tempAfter->next;
}
}
}