问题:
每次插入第二个位置的数字……
发生是因为在这部分代码中:
while(n!=NULL&&n->data > new->data){ // find which position num should insert in sorted list
n = n->next;
}
new->next = n->next;
n->next= new;
您将在n->next 之后插入新节点。
假设你的链表的第一个节点有数据16,现在你想在链表中插入数据45的新节点,while循环条件将失败,因为16 > 45将评估到false。
while 循环之后的语句new->next = n->next; 会将新节点的下一个节点设置为第一个节点的下一个节点,n->next= new; 将在第一个节点之后插入新节点。因此,新节点每次都插入到第二个位置。
您的函数insertSort() 存在更多问题,例如:
- 在向链表插入节点时不跟踪链表的
head,并且,
- 如果插入的节点是链表的第一个节点会怎样?在这种情况下,
n 将 NULL 和 insertSort() 在 while 循环之后访问 next 的 n - new->next = n->next;。
查看您给出的示例 - ,您希望按升序插入。
你可以这样做:
struct linkedList *insertSort(struct linkedList *n, int num, int *length) {
struct linkedList *first_node = n;
struct linkedList *new_node = malloc(sizeof(struct linkedList)); //create a new node
new_node->next=NULL;
new_node->data = num;
if (first_node == NULL || first_node->data >= new_node->data) {
new_node->next = first_node;
first_node = new_node;
} else {
struct linkedList *temp = first_node;
while (temp->next != NULL && temp->next->data < new_node->data) {
temp = temp->next;
}
new_node->next = temp->next;
temp->next = new_node;
}
*length += 1;
return first_node;
}
在这里,您可以看到我已将返回类型void 更改为struct linkedList *,以便在将新节点插入到链表中的适当位置后insertSort() 将返回链表的head。这样,您可以在每次插入后跟踪链表的head。你只需要这样做:
head = insertSort(head, num, &length);
无论您在哪里拨打insertSort()。
或者,如果你不想改变insertSort()的返回类型,你可以在insertSort()中传递head指针的地址并跟踪它,像这样:
void insertSort(struct linkedList **head, int num, int *length) {
struct linkedList *new_node = malloc(sizeof(struct linkedList)); //create a new node
new_node->next=NULL;
new_node->data = num;
if (*head == NULL || (*head)->data >= new_node->data) {
new_node->next = *head;
*head = new_node;
} else {
struct linkedList *temp = *head;
while (temp->next != NULL && temp->next->data < new_node->data) {
temp = temp->next;
}
new_node->next = temp->next;
temp->next = new_node;
}
*length += 1;
}
您可以像这样拨打insertSort():
insertSort(&head, 32, &length);
希望这会有所帮助。