当前位置: 动力学知识库 > 问答 > 编程问答 >

Append to the list in c

问题描述:

What is the correct way to append to a list in c? Ive been searching everywhere and everytime I try it myself I fail.

typedef struct node

{

char* groupName;

int groupSize;

boolean status;

struct node* next;

} node;

void add(struct node * *head)

{

struct node* temp=(struct node *)malloc(sizeof(node));

temp->groupName=name;

temp->groupSize=size;

if ((*head) == NULL) {

(*head) = temp;

(*head)->next = NULL;

} else {

struct node* ptr = (*head); //dont change head pointer, so make variable to keep track

while (ptr != NULL) ptr= ptr->next; //go until the end of the list

(ptr->next) = temp; //add this new data to the end of the list

temp->next = NULL; //null becomes end of list

}

}

call (in main():

add(&head);

网友答案:

The problem probably lies in this line of code:

   while(ptr!=NULL) ptr= ptr->next; //go until the end of the list

You change ptr until it's equal to NULL, which most definitely isn't what you want, since you dereference ptr right after the loop.

Change it to

   while(ptr->next != NULL) ptr = ptr->next;

and see if that works. Remember: you are interested in the node that doesn't yet have the next node (so you can insert it).

分享给朋友:
您可能感兴趣的文章:
随机阅读: