Example 1 — Append and walk both directions
Keep head and tail in a small struct.
#include <stdio.h>
#include <stdlib.h>
struct DNode { int data; struct DNode *prev, *next; };
struct DList { struct DNode *head, *tail; };
static void push_back(struct DList *l, int v) {
struct DNode *n = malloc(sizeof *n);
if (!n) exit(1);
n->data = v;
n->next = NULL;
n->prev = l->tail;
if (l->tail) l->tail->next = n;
else l->head = n;
l->tail = n;
}
int main(void) {
struct DList list = {NULL, NULL};
for (int i = 1; i <= 3; i++) push_back(&list, i);
printf("forward:");
for (struct DNode *p = list.head; p; p = p->next) printf(" %d", p->data);
printf("\nbackward:");
for (struct DNode *p = list.tail; p; p = p->prev) printf(" %d", p->data);
printf("\n");
while (list.head) {
struct DNode *t = list.head->next;
free(list.head);
list.head = t;
}
return 0;
} How It Works
- Each new node points back to the old tail with
prev. - The old tail points forward to the new node with
next. - Walking
prevfrom the tail gives the reverse order.
