我正在尝试编写一个函数,将数字(从用户)插入节点(每个节点1个数字),然后以递增的方式对它们进行排序。 我写了这个函数:
void insertnode(struct n_node *head)
{
struct n_node *temp = head;
int number;
printf("Please insert a number to the node\n");
scanf("%d", &number);
while (number != SENTRY)
{
while ((temp->next != NULL) && (temp->next->num < number))
{
temp = temp->next;
}
struct n_node *addNode = (struct n_node*)malloc(sizeof(struct n_node));
addNode->num = number;
if (temp->next == NULL && number < temp->num)
{
addNode->next = temp;
head = addNode;
}
else
{
addNode->next = temp->next;
temp->next = addNode;
}
temp = head;
scanf("%d", &number);
}
options();
}
它编译但是在我插入第一个数字后停止,给我一个中断消息并指向这一行:
while ((temp->next != NULL) && (temp->next->num < number))
错误列表中没有任何内容,感谢任何帮助,谢谢!
答案 0 :(得分:2)
在您的算法中,您没有按正确的顺序测试特殊情况:
head
为NULL
且测试temp->next != NULL
调用未定义的行为。您应首先分配新节点并使用单个测试检查特殊情况:
struct n_node *addNode = malloc(sizeof(struct n_node));
addNode->num = number;
if (head == NULL || number < head->num) {
addNode->next = head;
head = addNode;
}
否则,您的迭代循环是正确的,当您到达错误条件时,将在temp
之后插入节点:
while (temp->next != NULL && temp->next->num < number) {
temp = temp->next;
}
addNode->next = temp->next;
temp->next = addNode;
循环变得更加简单:
void insertnode(struct n_node **headp) {
struct n_node *head = *headp;
int number;
printf("Please insert a number to the node\n");
while (scanf("%d", &number) == 1 && number != SENTRY) {
struct n_node *addNode = malloc(sizeof(struct n_node));
if (addNode == NULL) {
printf("out of memory\n");
return;
}
addNode->num = number;
if (head == NULL || number < head->num) {
addNode->next = head;
*headp = head = addNode;
} else {
struct n_node *temp = head;
while (temp->next != NULL && temp->next->num < number) {
temp = temp->next;
}
addNode->next = temp->next;
temp->next = addNode;
}
}
options(); // head is not passed to the function?
}
还要注意API中的更改以允许函数更新调用者范围内的列表头,更改为在文件结束时停止扫描数字或者除了幻数之外还停止非数字输入。