c - 在链表中插入

标签 c data-structures linked-list

我正在研究如何在开始时插入节点,我通过这段我无法理解的代码。
我没有得到打印功能。

typedef struct node
{
    int data;
    struct node *next;
} Node;
Node *head;
void insert(int x)
{
    Node *temp=(Node*)malloc(sizeof(Node));   
    temp->data=x;
    temp->next=head;
    head=temp;
}
void print()
{
    Node *temp=head;
    printf("List is:");
    while(temp!=NULL) //Unable to understand this statement as how will the loop terminate?                  
    {
        printf("%d ",temp->data);
        temp=temp->next;
    }
    printf("\n");
}

最佳答案

假设你的链表看起来像

a->b->c->d
|
|
head

所以现在我们使用一个临时变量

temp = head;

while(temp != NULL)
{
  //Keep moving temp
  printf("%d\n",temp->x);
  temp = temp->next;
}

所以 head 永远不会移动,它只是移动到列表末尾的临时指针,当我们到达 temp = NULL 时,列表的末尾就到了

a->b->c->d
|
|
temp = head

temp = temp->next;

    a->b->c->d
    |  |
    |  |
  head temp

重复上述操作直到 temp = NULL 当最后一个节点内容被打印时为 TRUE,我们执行 temp = temp->next;

关于c - 在链表中插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28432270/

相关文章:

java - 是否有一种类似 C 的迷你语法/语言可以同时翻译为 native C/C++ 和 Java?

c# - 我想了解更多有关 LinkedList<T> 的信息

c - 从文件写入和读取结构或在 c 中相反

c++ - 从不同进程通过套接字 (UDP) 回复客户端

c++ - 简化三次贝塞尔路径?

c - 在没有内存泄漏的情况下替换函数中的 char*

algorithm - 计数子数组的总和在 [L, R] 范围内

algorithm - "uniform-cost search"算法中的路径如何获取?

哈希表数据结构中的冲突

java - 为什么没有 LinkedList.join() 方法来在 O(1) 时间内合并两个未排序的列表?