I have seen quite a few examples of implementing C linked lists on this site, and most of them put the following pointer at the end of each node, like this ...
struct intNode1 {
int data;
intNode1 *next;
};
Why do they implement them like this instead?
struct node {
struct node *next;
};
struct intNode2 {
struct node node;
int data;
};
The last way to implement linked lists allows your insert and delete code to work with any type of node, and it also allows you to create a general type of list, while the previous way forces you to implement each kind of list from scratch.
For example, here is a (incomplete) implementation of a singly linked list using both types of nodes:
struct intList {
struct intNode1 *head;
};
struct list {
struct node *head;
};
, , , , , . :
int list-insertInt(struct list *list, int n) {
struct intNode2 * newNode;
if(!(newNode = malloc(sizeof *newNode)) {
return -1;
}
newNode->data = n;
return list-insertNode(list, (struct node *)newNode);
}
int list-containsInt(struct list *list, int n) {
struct intNode2 *current = (intNode2 *)list->head;
while (current) {
if(current->data == n) {
return true;
}
current = current->next;
}
return false;
}
, , free
, , :
void list-free(struct list *list) {
struct node *current = list->head;
struct node *next;
while(current) {
next = current->next;
free(current);
current = next;
}
}
PS. (.. , ), . , .