双链尾部删除o(1)时间

时间:2020-10-25 22:52:54

标签: c doubly-linked-list tail

我正在尝试使用尾指针从链接列表的末尾删除,但我似乎无法获取。

typedef struct node
{
    int data;
    struct node *next;
    struct node *prev;
} node;

typedef struct LinkedList
{
    node *head;
    node *tail;
} LinkedList;

// Deletes from the head of the list using a head                                 pointer
void doubly_head_delete(LinkedList *list)
{
    if (list->tail->prev == NULL)
    {
        list->head = list->head->next;
        list->head->prev = NULL;
    }
    else
    {
        list->tail->prev->next = list->tail->next;
        list->tail->next->prev = list->tail->prev;
    }
}

// Deletes the tail of the list using a tail pointer
void doubly_tail_delete(LinkedList *list)
{
    if (list == NULL || list->head == NULL)
        return;
    if (list->head != list->tail)
    {
        list->tail = list->tail->prev;
        list->tail->next = NULL;
        list->tail = list->tail->prev;
    }
    else
    {
        list->head = list->tail = NULL;
    }
}

我不认为尾部删除功能有效,因为我不知道如何正确释放尾部。另外,我不确定如何将尾部指针设置到列表的尾部。至于head_delete(),它似乎正在工作,但我不确定具体如何运行,或者它是否确实正确,或者它只是巧合而已。我仍在尝试学习这一点,互联网似乎没有最好的例子。谢谢

1 个答案:

答案 0 :(得分:2)

在更改指针之前,您需要保留地址。

void doubly_tail_delete(LinkedList *list)
{
   if (list == NULL || list->head == NULL)
      return;
   if (list->head != list->tail)
   {
       node *todelete = list->tail;
       list->tail = list->tail->prev;
       list->tail->next = NULL;
       //the next line you had is wrong.
       //list->tail = list->tail->prev;
       free(todelete);
   }
   else
   {
      free(list->head); //free it here before setting as NULL otherwise you lose the reference.
      list->head = list->tail = NULL;
   }
}

从头部删除时,您也没有释放...而且上面有一些错误。

void doubly_head_delete(LinkedList *list)
{
   if (list == NULL || list->head == NULL)
      return;

   if (list->tail->prev == NULL)
   {
       free(list->head);
       list->head = list->tail = NULL;
   }
   else
   {
       node *todelete = list->head;
       list->head = list->head->next;
       list->head->prev = NULL;
       free(todelete);
   }
}
相关问题