简体   繁体   English

基于位置的C双链表插入

[英]C double linked list insert based on location

I am working on a generic form of a double linked list, so I have : 我正在研究双链表的通用形式,所以我有:
list structure : 列表结构:

int size;  
struct elem *head;  
struct elem *current;  
struct elem *tail;

elem structure : elem结构:

void *data;  
struct elem *next;  
struct elem *prev;

I am having a hard time implementing a function allowing me to push a new element before the current one. 我很难实现一个允许我在当前元素之前推送新元素的函数。 Here is what I came up with for the moment : 这就是我现在想出来的:

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);
}

But my list->head->next seem to point to NULL . 但我的list->head->next似乎指向NULL What is the issue? 有什么问题?

您应该 list->current->prev 之前修改list->current->prev->next ,目前您有效地执行elem->next = elem

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM