I am attempting to implement a circular linked list, but it is not working as I expected. Even though I insert two elements with insertAfter
, printList
only prints one node. Here is a minimal example:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct dnode_elm {
int item;
struct dnode_elm *next, *prev;
};
struct dnode_elm *
insertAfter(struct dnode_elm *a, int value) {
struct dnode_elm *v= malloc(sizeof(struct dnode_elm));
v->item=value;
a->next=v;
v->prev=a;
v->next=a->next;
a->next->prev=v;
return v;
}
void
printList(struct dnode_elm *h) {
while (h != h->next) {
h = h->next;
printf("%d --> ",h->item);
}
}
int
main(void) {
struct dnode_elm h = { INT_MAX, &h, &h };
insertAfter(&h, 1);
insertAfter(&h, 2);
printList(&h);
}