【问题标题】:doubly linked tail delete o(1) time双链尾删除 o(1) 时间
【发布时间】:2023-03-08 23:55:01
【问题描述】:

我试图使用尾指针从链表的末尾删除,但我似乎无法得到它。

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(),它似乎正在工作,但我不确定它究竟是如何工作的,或者它是否真的正确,或者它是否只是一个巧合。我仍在努力学习这一点,互联网似乎没有最好的例子。谢谢

【问题讨论】:

  • 你的两个删除函数应该完全一样,除了“head”和“tail”应该颠倒,“next”和“prev”应该颠倒。如果不是这样,那么其中一个可能有错误,对吧?

标签: c doubly-linked-list tail


【解决方案1】:

更改指针前需要保留地址。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 2019-04-11
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多