c - 删除链表尾部 : Why a specific approach won't work

标签 c function pointers struct linked-list

我试图理解为什么某个函数会删除链表的尾部而不是另一个。

这是我的链表结构:

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

我的尾插入实现:

node *tail_insert(node *head, int data)
{
    node *temp;

    if (head == NULL)
        return create_doubly_node(data);

    for (temp = head; temp->next != NULL; temp = temp->next)
        ;

    temp->next = create_doubly_node(data);
    temp->next->prev = temp->next;

    return head;

}

这个函数删除尾部:

node *tail_delete(node *head)
{
    node *temp, *prev;

    if (head == NULL)
        return head;

    temp = head;

    while (temp->next != NULL)
    {
        prev = temp;
        temp = temp->next;
    }

    free(temp);
    prev->next = NULL;

    return head;
}

相对于这个:

node *tail_delete(node *head)
{
    node *temp, *prev;

    if (head == NULL)
        return head;

    temp = head;

    while (temp->next != NULL)
    {
        temp = temp->next;
    }

    prev = temp->prev;
    free(temp);
    prev->next = NULL;

    return head;
}

区别在于我如何分配节点 *prev。

最佳答案

您的以下语句是错误的,因为您的 prev 指针指向错误的节点,您的第二种方法不起作用:-

temp->next->prev = temp->next; //here prev is pointing to itself
                               //actually prev = create_doubly_node(data);

更正为:-

 temp->next->prev = temp; //as temp is pointing to the previous node of last node

关于c - 删除链表尾部 : Why a specific approach won't work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48755191/

相关文章:

c - 我的 Mandelbrot 集代码有什么问题?

创建一个文本文件,其中文件名基于一个或两个数组中的值

c - 找到硬编码号码

每 3 秒调用一次函数

php - MySQL添加函数计算变量

c - GCC 是否为传递给函数的数组创建 typedef?

c - 使用指针对 3 个 double 值进行排序

C 指针数组未按预期打印,它用最后一个输入替换所有内容

r - "vectorize"具有不同参数长度的函数的最快方法

pointers - 为 Phobos 的二进制堆比较指向结构的指针