Question: I need help creating a doubly linked list in C. The program is supposed to create a doubly-linked list, fill it with different letters as
I need help creating a doubly linked list in C. The program is supposed to create a doubly-linked list, fill it with different letters as shown, then verify the values, clear the list and delete it. Feel free to edit and fill in any functions except for: list_insert, list_first and list_end.
// The type for a node in the list. struct node { struct node *next; struct node *prev; char *value; }; // The type for a list. typedef struct list { struct node head; } List; // The type for a list position. typedef struct list_pos { struct node *node; } ListPos; // Create and return an empty list. List *list_create(void); // Deallocate the list (and all of its values, if any). void list_destroy(List *lst); // Check if the list is empty. bool list_is_empty(const List *lst); // Get the position of the first element. ListPos list_first(List *lst); // Get the position after(!) the last element. ListPos list_end(List *lst); // Check equality between two positions. bool list_pos_equal(ListPos p1, ListPos p2); // Forward to the next position. ListPos list_next(ListPos pos); // Backward to the previous position. ListPos list_prev(ListPos pos); // Insert the value before the position and return the position of the new element. ListPos list_insert(ListPos pos, const char *value); // Remove the value at the position and return the position of the next element. ListPos list_remove(ListPos pos); // Get the value at the position. const char *list_inspect(ListPos pos); static char *clone_string(const char *in) { size_t len = strlen(in); char *out = calloc(len + 1, sizeof(char)); strcpy(out, in); return out; }
ListPos list_first(List *lst) { ListPos pos = { .node = lst->head.next }; return pos; } ListPos list_end(List *lst) { ListPos pos = { .node = &lst->head }; return pos; } ListPos list_insert(ListPos pos, const char *value) { // Create a new node. struct node *node = make_node(value); // Find nodes before and after (may be the same node: the head of the list). struct node *before = pos.node->prev; struct node *after = pos.node; // Link to node after. node->next = after; after->prev = node; // Link to node before. node->prev = before; before->next = node; // Return the position of the new element. pos.node = node; return pos; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
