【发布时间】:2021-02-02 05:39:19
【问题描述】:
我正在尝试在 C 编程语言中对双向链表执行插入排序功能。当我在一个双向链表上运行这个函数的代码时 13749 我得到一个排序的输出。但是,当我在 53749 的双向链表上运行此代码时,我得到一个空白输出(是的仍然编译和运行)。
我无法弄清楚为什么当第一个节点的值大于第二个节点时它返回空白输出。我猜这与我的 if 语句有关?
void insertion_sort_increasing(struct List *list)
{
struct Node *current_node = list->head; //initialize current_node
struct Node *tempA;
struct Node *tempB;
struct Node *tempC;
struct Node *tempD;
if (current_node == NULL) {
printf("Empty List.");
} else {
current_node = current_node->next;
while (current_node != NULL) { //iterates doubly linked list
if (current_node->prev->StudentID > current_node->StudentID) {
tempA = current_node; //(3 in this case)
tempB = current_node->prev->prev; //(NULL in this case)
tempC = tempA->next->prev;
tempD = tempB->next;
tempA->next->prev = tempA->prev; // 5<--7
tempB->next->prev = tempC; // 3<--5
tempB->next = tempA->prev->next; // NULL-->3
tempA->prev->next = tempA->next; // 5-->7
tempA->next = tempD; // 3-->5
tempA->prev = tempD->prev; // NULL<--3
if (tempB == NULL) {
list->head = tempB->next; // 3 = head
}
}
current_node = current_node->next;
}
}
}
【问题讨论】:
-
请发帖minimal reproducible example 并选择一种语言。适合 C++ 的东西不适合 C,反之亦然。
-
请详细说明并解释返回空白是什么意思?你是如何测试代码的?请同时添加该代码。
-
顺便说一句:我认为这不是插入排序。那里有大量节点指针,但我认为我没有看到输出列表。
-
我会注意到,不可能只用一个循环对一个非平凡的未排序列表进行排序。您需要做的是从输入列表中弹出项目,并将它们插入到输出列表中的适当位置。因此,您有一个用于弹出每个节点的外循环,以及一个遍历输出循环的内循环(最好将其放在
SortedInsert()函数中)以找到它刚刚从输入列表中弹出的节点的正确位置。 -
这是学习如何使用调试器的好时机。或者在你的代码中插入一些
printf()s。此外,jwdonahue 的回答是很好的建议。
标签: c doubly-linked-list