logo

Deallocating a doubly linked list

#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct Node { int x; struct Node* next; struct Node* prev; } Node; void deallocate(Node** tail, Node** head) { if (*tail == NULL) { return; } Node* curr = *tail; while (curr->next != NULL) { curr = curr->next; free(curr->prev); } free(curr); *tail = NULL; *head = NULL; } int main(int argc, char* argv[]) { Node* tail = malloc(sizeof(Node)); if (tail == NULL) { return 1; } tail->x = 1; tail->prev = NULL; tail->next = malloc(sizeof(Node)); if (tail->next == NULL) { return 2; } tail->next->x = 3; tail->next->prev = tail; tail->next->next = malloc(sizeof(Node)); if (tail->next->next == NULL) { return 3; } tail->next->next->x = 7; tail->next->next->prev = tail->next; tail->next->next->next = NULL; Node* head = tail->next->next; deallocate(&tail, &head); return 0; }
Course thumb

The C programming language made simple