Originally posted by MKashlev
Code:
struct node* AppendNode(struct node** headRef, char var[50]) {
struct node* current = *headRef;
struct node* newNode;
newNode = malloc(sizeof(struct node));
newNode->data = var;
newNode->next = NULL;
// special case for length 0
if (current == NULL) {
*headRef = newNode;
}
else {
// Locate the last node
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
Code:
void AppendNode(struct node** headp, char var[50]) {
struct node *currentp, *previousp, *newp;
currentp = previousp = newp = NULL;
newp = malloc(sizeof(struct node) );
//Perform deep copy
strcpy( newp->data,var );
newp->next = NULL;
// special case for length 0
if (*headp == NULL) {
**headp = *newp;
}
else {
// Locate the last node
currentp = headp;
while (current->next != NULL) {
previousp = currentp;
current = current->next;
}
previousp->next = newp;
}
}
I forget, it's been ages, but the code for adding a node goes something like this. There are sure to be a few errors. I did not test the code, but this is the basic idea for appending a node to a linked list. You don't need to return the list because your using a pointer to a pointer. Someone else can fix the errors.