如何在C的循环链接列表中插入节点

问题描述

有人可以解释代码的“ 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;
}

解决方法

有人可以解释代码的“ while部分”吗?

while()部分(也在下面的2.)部分中进行了介绍。)将查找指向当前 head节点的节点,以便 new节点可以在其之前插入。在循环中,请注意,当找到节点并且它们还不是 head节点时,它们会被递增以便为 head插入做准备节点终于找到了。

例程中的最后一个表达式:

*head_ref = ptr1;

用于处理以下常规步骤中第1.)节所述的情况。

以下初始条件的一般方法:

  1. 链接列表为空:
    a)由于new_node是CLL中的唯一节点,因此进行自循环。
    new_node-> next = new_node;
    b)更改头指针以指向新节点。 * head_ref = new_node;
  2. 要在头节点之前插入新节点:
    (a)使用循环找出最后一个节点。 while(当前->下一个!= * head_ref) 当前=当前->下一个; (b)更改最后一个节点的下一个。 当前->下一个= new_node; (c)将新节点的下一个更改为指向头。 new_node-> next = * head_ref; (d)更改头指针以指向新节点。 * head_ref = new_node;
  3. 将在头之后的某个位置插入新节点: (a)找到要在其后插入新节点的节点。 while(当前->下一个!= * head_ref && 当前->下一个->数据数据) {current = current-> next; } (b)将new_node的下一个作为所定位指针的下一个 new_node-> next =当前-> next; (c)更改下一个指针的位置 current-> next = new_node;

example code

中显示了执行此操作的详细信息和实现