我正在研究双链表的通用形式,所以我有:
列表结构:
int size;
struct elem *head;
struct elem *current;
struct elem *tail;
elem结构:
void *data;
struct elem *next;
struct elem *prev;
我很难实现一个允许我在当前元素之前推送新元素的函数。这就是我现在提出的问题:
t_list *my_list_add_before(t_list *list, void *data)
{
struct elem *elem = malloc(sizeof(*elem));
elem->data = data;
if(list->size == 0)
{
list->head = elem;
list->current = elem;
list->tail = elem;
elem->prev = NULL;
elem->next = NULL;
}
else
{
elem->next = list->current;
elem->prev = list->current->prev;
elem->prev->next = elem;
list->current->prev = elem;
}
list->size = list->size + 1;
return (list);
}
但我的list->head->next
似乎指向NULL
。有什么问题?
答案 0 :(得分:2)
您应该在 list->current->prev->next
之前修改list->current->prev
,目前您实际上是elem->next = elem
。