链表遍历**与(thead!= NULL)**和while(thead-> next!= NULL)之间的差异

任何人都可以告诉我while(thead!= NULL)while(thead-> next!= NULL)之间的区别是什么因为遍历列表thead!= NULLthead-> next工作时不起作用 。 根据我的理解,head节点只是指向起始节点的指针,而不是起始节点本身。
如果你有疑问,请看这个 。这里只是存储地址。

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

#include #include #include 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替换thead – > next!= NULL!= NULL然后dev c ++停止工作。反之亦然printf for traversal …

那么有人可以回答上述两者之间的差异吗?

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

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

什么时候是一个结构为NULL的指针?

谢谢

使用print() ,代码不需要记住循环后的最后一个节点地址

 temp=head; while(temp!=NULL) { printf("%d",temp->data); temp=temp->next; } // temp == NULL at this point and code does not care what the last node was. 

使用insert() ,代码确实需要记住循环后的最后一个节点地址。

 // First handle special case where the head of the list is NULL // otherwise .... while(thead->next!=NULL) { thead = thead->next; } // temp->next == NULL at this point // Code can use `thead` to access the last node's members. thead->next = temp; 

头节点是第一个包含数据和地址的节点,还是只存储上图中的地址?

struct node *head是一个指针。 当head != NULL ,它指向包含数据和下一个指针的frist节点。

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

theadhead初始化。 通过取消引用thead ,代码可以访问该节点的成员,包括.next

when是指向结构NULL的指针?

问题不清楚。 当struct的值等于NULL时,指向struct的指针为NULL 。 这通常是链表代码中使用的结尾。

既然我已经明白……对于那些仍然被困的人我正在写这个……

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

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

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