[英]having hard time debugging deletion of head node in a circular linked list
I'm learning data structures and was practicing questions on circular linked list.我正在学习数据结构并且正在练习循环链表上的问题。 So, i'm supposed to write a function which deletes the
head
node of a circular linked list, so i came up with this code -所以,我应该写一个 function 来删除循环链表的
head
节点,所以我想出了这段代码 -
void del_head(struct node** head, struct node** tail)
{
struct node* new_head = (*head)->next;
free(*head);
*head = new_head;
(*tail)->next = *head;
}
After debugging i found that the tail
is not getting updated.调试后我发现
tail
没有得到更新。
I'm having tough time trying to find the problem.我很难找到问题所在。
Any help is appreciated, thanks任何帮助表示赞赏,谢谢
After debugging i found that the
tail
is not getting updated.调试后我发现
tail
没有得到更新。
Your code will work perfectly fine for a circular list having more than 1
node and since you are deleting head
node, so if the list will have more than 1
node, tail
will be pointing to same node after head
node deletion as it was pointing to a node before deletion.对于具有
1
个以上节点的循环列表,您的代码将完全正常工作,并且由于您正在删除head
节点,因此如果列表将具有1
个以上节点,则在删除head
节点后, tail
将指向相同的节点,因为它指向删除前的节点。
Consider a case where the circular list has only one node:考虑循环列表只有一个节点的情况:
head---+
|
tail----+ |
| |
---------------
| data | next |-------+
--------------- |
| |
+------------------+
head
, tail
and node next
all are pointing to same node. head
, tail
和 node next
都指向同一个节点。
For this scenario, your code will end up accessing a deallocated memory.对于这种情况,您的代码最终将访问已释放的 memory。
You can do:你可以做:
void del_head(struct Node** head, struct Node** tail) {
// validate head and tail pointer
if (!(head && *head)) {
printf ("Invalid head pointer\n");
return;
}
if (!(tail && *tail)) {
printf ("Invalid tail pointer\n");
return;
}
struct Node* x = *head;
if (*tail == x) {
// the circular list has only one node
*head = *tail = NULL;
} else {
*head = (*tail)->next = x->next;
}
x->next = NULL;
free(x);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.