c - 链表遍历**while(thead != NULL)**和while(thead->next !=NULL)的区别

标签 c pointers linked-list

谁能告诉我 while(thead != NULL)while(thead->next !=NULL) 之间的区别是什么,因为遍历列表 < strong>thead != NULL 不工作,而 thead->next 工作。 根据我的理解,头节点只是指向起始节点的指针,而不是起始节点本身。
See this if u have doubt .这里head只是存储地址。

//thead 表示临时头变量,用于存储头指向的地址。
这是插入代码。

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

struct node
{
    int data;
    struct node *next;
};
struct node *head;
void insert(int x)
{
    struct node *temp=(struct node *)malloc(sizeof(struct node));   
    temp->data=x;   
    temp->next=NULL;   
    if(head==NULL)     
    {     
         head=temp;    
    }
    else
    {
        struct node * thead;
        thead=head;  
        while(thead->next!=NULL)
        {
            thead=thead->next;  
        }
        thead->next=temp;
    }
}

void print()
{
    struct node *temp;
    temp=head;
    while(temp!=NULL)
    {

        printf("%d",temp->data);
            temp=temp->next;
    }
}
int main()
{
    head=NULL;
    int i,n,x;
    printf("enter number of nodes");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        printf("enter no");
        scanf("%d",&x);
        insert(x);
    }
    print();
}

如果我们将 thead ->next != NULL 替换为 thead !=NULL 那么 dev c++ 将停止工作。反之亦然发生在遍历的 printf ...

那么有人能解答一下上面两者的区别吗?

此外,头节点是包含数据和地址的第一个节点,还是像上图那样只存储地址?

此外,如果头节点只是一个存储地址的指针,那么我们如何访问 thead->next ?

什么时候指向结构的指针为 NULL?

谢谢

最佳答案

既然我已经真正理解了....对于那些仍然卡住的人我正在写这个......

当我使用 (thead!=NULL) 时,thead 指针实际上指向列表中的每个元素。当它到达最后一个元素时,它仍然遍历到下一个为 NULL 的元素,这与 (thead->next! =NULL) 停止在链表的最后一个元素。

在 print 的情况下,我们需要打印列表中的所有值,所以我们使用 while(thead!=NULL) 因为我们也需要打印最后一个元素。对于遍历,我们只需要使指针指向最后一个节点,这样我们就可以停在它处,直到我们到达 NULL 指针才遍历。

我们无法取消引用 NULL,因此出现错误。

关于c - 链表遍历**while(thead != NULL)**和while(thead->next !=NULL)的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44530609/

相关文章:

C结构链表段错误

c - Schönauer Triad 基准 - L1D 缓存不可见

无法增加共享内存的大小

pointers - [Golang]指针类型、指针类型和结构体类型调用方法有什么不同?

c - C 中带有指向其他结构数组指针的结构的问题

c - 关于指针指向指针的问题

c - 如何在链表中向后移动?

c - 链表 K 交替逆向程序

c - 请检查我的 segFault

c - GNU C 使用管道的多进程处理