我试图理解为什么某个函数会删除链表的尾部而不是另一个。
这是我的链表结构:
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/