【发布时间】:2017-11-15 18:28:34
【问题描述】:
谁能告诉我 while(thead != NULL) 和 while(thead->next !=NULL) 有什么区别,因为用于遍历列表 thead != NULL 不工作,而 thead->next 工作。
据我了解,头节点只是指向起始节点的指针,而不是起始节点本身。
See this if u have doubt.这里的头只是存储地址。
//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->next==NULL条件在此范围内意味着什么? -
如果 thread 等于 NULL,则 thread->next = temp 尝试取消引用 NULL 指针。
-
@AbhishekBansal 你提到的条件在这个算法中可能吗?
-
如果代码使用
while(thead != NULL) { ... },那么在循环之后,应该将什么设置为temp?需要设置为temp的是一些.next成员,但是什么指针?
标签: c pointers linked-list