与我之前的帖子相关Editing a node in a Linked list .我在编辑节点时完成了以下步骤:
- 编辑目标节点数据
- 移除目标节点
- 重新插入目标节点
问题是我无法按如下所示将其重新插入到节点的顶部....
std1 90 -> std 2 50 -> std3 20 -> NULL
我把std3改成了100,结果会是这样
std2 50 -> std3 20 -> NULL
简而言之,我不能把它放回顶部节点。重新插入顶级节点以外的任何地方都可以正常工作。
最佳答案
如果头节点是 97%,而你通过了一个 97% 的节点,你就会遇到问题。你需要说
while (curr_std != NULL && to_add->grade <= curr_std->grade){
如果您正在编辑的学生是第一个节点,您也会遇到问题,因为:
while((cur != NULL) && (strcmp(cur->name,temp) != 0)){
将评估为真,并且
prev = cur;
永远不会被调用,离开prev
= 空。然后当你到达p>
prev->next = cur->next;
你有一个空引用。您需要显式测试添加到头节点;这是它自己的特例。
scanf("%d", &(cur->grade));
if (prev == null) { // you matched the head
head = cur->next;
}
else {
prev->next = cur->next;
}
编辑
当你添加到头部时,在你的代码中,你还没有将头部设置为指向你的新节点。您正在返回旧头,它现在指向列表中的第二个节点。尝试:
while (curr_std != NULL && to_add->grade < curr_std->grade){
prev_std = curr_std;
curr_std = curr_std->next;
}
// if you're adding to the head, you didn't go into the above loop
// curr_std is still pointing to head in this case
if (curr_std == head) {
head = to_add
}
else {
prev_std->next = to_add;
}
to_add->next = curr_std;
return head;
关于c - 编辑链表中的节点 Part2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4401070/