【发布时间】:2020-09-17 16:06:39
【问题描述】:
有人可以解释代码的“while 部分”吗?- 在 main() 头中声明为结构节点指针,初始化为 NULL。并通过调用 function = push(&head,12) 插入一个节点
void push(struct Node **head_ref, int data)
{
struct Node *ptr1 = (struct Node *)malloc(sizeof(struct Node));
struct Node *temp = *head_ref;
ptr1->data = data;
ptr1->next = *head_ref;
if (*head_ref != NULL)
{
while (temp->next != *head_ref)
temp = temp->next;
temp->next = ptr1;
}
else
ptr1->next = ptr1; /*For the first node */
*head_ref = ptr1;
}
【问题讨论】:
-
在下面的答案中,我试图解决您的问题,但如果还不够,请在有任何问题的评论中标记我 (@ryyker) :))
-
循环链表中缺少指向最后一个节点的指针(由双向链表中的
->prev指针提供)要求添加新的第一个节点后,必须遍历整个列表找到最后一个节点并更新->next指针,使其指向新的第一个节点。 (课程:始终保留tail指针或将列表设为doubly-linked列表以保留 O(1) 插入)
标签: c linked-list circular-list