'How to create an empty doubly-linked list in C?
I wrote most of the code for my doubly linked list in C, but it seems that the reason I'm struggling to add values into the list is due to a mistake I made when creating an empty doubly linked list. Here's my attempt at it, what am I doing wrong here and how would I go about fixing it?
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;
List *list_create(void)
{
List *lst = (List*)malloc(sizeof(List));
if(lst == NULL)
{
printf("No more memory!\n");
return 0;
}
return lst;
}
static struct node *make_node(const char *value)
{
struct node *result = malloc(sizeof(struct node));
result->value = strdup(value);
result -> next = NULL;
result -> prev = NULL;
return result;
}
Example usage: main function: List *lst = list_create(); from function add_values():
static void add_values(List *lst) {
char str[2] = "A";
ListPos pos = list_first(lst);
for (char ch = 'A'; ch <= 'Z'; ch++) {
str[0] = ch;
pos = list_insert(pos, str);
pos = list_next(pos);
}
}
Implementation of functions:
int main(void){
List *lst = list_create();
...
}
add_values static void add_values(List *lst) {
char str[2] = "A"; ListPos pos = list_first(lst);
for (char ch = 'A'; ch <= 'Z'; ch++) {
str[0] = ch;
pos = list_insert(pos, str);
pos = list_next(pos);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
