2010-12-09 56 views
2

与我之前发布的帖子相关Editing a node in a Linked list。我已经做了在编辑节点以下步骤:编辑链接列表中的节点Part2

  1. 编辑目标节点数据
  2. 删除目标节点
  3. 重新插入目标节点

的问题是,我不能再插入AT如下节点的TOP ....

std1 90 -> std 2 50 -> std3 20 -> NULL 

我编辑STD3到100,结果会是这样

std2 50 -> std3 20 -> NULL 

总之,我不能把它放回顶层节点。重新插入除顶层节点以外的任何地方都可以正常工作。

+1

什么不起作用?插入错误位置,未插入,其他条目丢失,分段错误,...? – 2010-12-09 17:12:47

+0

如果您插入与另一个年级相同的学生,则会中断。 insert_student中的while循环不会执行,因此对prev_std-> next的赋值将失败,因为prev_std仍然为NULL。 insert_student中的其中一个条件需要包含“=”以及小于或大于 – 2010-12-09 17:17:29

回答

1

如果头节点为97%,并且您传递的节点为97%,则会出现问题。你需要说

while (curr_std != NULL && to_add->grade <= curr_std->grade){ 

您也将有一个问题,如果您正在编辑的学生是第一个节点,因为这:

while((cur != NULL) && (strcmp(cur->name,temp) != 0)){ 

将评估为真,

prev = cur; 

将永远不会被调用,而留下prev = null。然后当你到达

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;