Kazade said: ...
In short, there is nothing wrong with the code you just posted, but there is something wrong with the lists head.
+1.
Initially the list contains no nodes; upon inserting a new node (say the first node), the code needs to check if the head pointer is pointing to anything sane, or just pointing to null.
When the list is created (in the main function?), the head pointer should be set to null to indicate that the list is empty.
[php] int main() { struct list myList; myList.head = NULL;
struct node* n = malloc(sizeof(struct node)); // init node with whatever data it holds
link_node(&myList, n);
... }
void link_node(struct list* ls, struct node* node) { assert(ls != NULL); assert(node != NULL);
if (ls->head == NULL) { // add first node to list ls->head = node; ls->head->prev = NULL; ls->head->next = NULL; } else { // list exists; insert node at the beginning of the list node->next = ls->head; node->prev = ls->head->prev; // will always be null ls->head = node; } } [/php]
Unless you have a compelling reason to have a struct list, I would compose the "list" from using struct node elements. That's really all you need. Declare a head node, and set it equal to NULL. Then pass that to link_node() in lieu of the struct list.