开发者

Editing a node in a Linked list Part2

Related to my previous post Editing a node in a Linked list. I've done the following steps in editing the node:

  1. 开发者_JAVA百科Edit target node data
  2. Remove target node
  3. Re-insert target node

THE PROBLEM IS THAT I CANNOT RE-INSERT IT AT THE TOP OF THE NODE as follows....

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

I edited std3 to 100. The result will be like this

   std2 50 -> std3 20 -> NULL

In short, i cannot put it back on the top node. Re-inserting anywhere other than the top node works fine.


You'll have an issue if the head node is a 97%, and you pass a node with a 97%. You need to say

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

You'll also have an issue if the student you're editing is the first node, because this:

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

will evaluate to true, and

prev = cur;

will never get called, leaving prev = null. Then when you get to

prev->next = cur->next;

you have a null reference. You need to explicitly test for adding to the head node; it's its own special case.

scanf("%d", &(cur->grade));
if (prev == null) {  // you matched the head
    head = cur->next;
}
else {
    prev->next = cur->next;
}


EDIT
When you add to the head, in your code, you haven't set the head to point to your new node. You're returning the old head, which now points to the second node in the list. Try:

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜