logo

Add to the beginning of a doubly linked list

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; } void insert_beginning(Node** tail, int value) { Node* new_node = malloc(sizeof(Node)); if (new_node == NULL) { exit(1); return; } new_node->x = value; new_node->prev = NULL; new_node->next = *tail; (*tail)->prev = new_node; *tail = new_node; } void init(Node** tail, Node** head, int value) { Node* new_node = malloc(sizeof(Node)); if (new_node == NULL) { exit(2); return; } new_node->x = value; new_node->prev = NULL; new_node->next = NULL; *tail = new_node; *head = new_node; } int main(int argc, char* argv[]) { Node* tail = NULL; Node* head = NULL; init(&tail, &head, 7); insert_beginning(&tail, 3); insert_beginning(&tail, 1); for (Node* curr = head; curr != NULL; curr = curr->prev) { printf("%d ", curr->x); } deallocate(&tail, &head); return 0; }
Course thumb

The C programming language made simple