我试图理解为什么某个函数会删除链表的尾部而不是另一个。
这是我的链表结构:
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。
存在差异答案 0 :(得分:2)
你的下面的语句是错误的,因为你的前一个指针指向一个错误的节点你的第二个方法不起作用: -
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