[英]confusion in making of a linked list
我正在尝试理解创建和显示链接列表的代码
#include <stdio.h>
#include <stdlib.h>
int create(int n);
void print();
struct node
{
int data;
struct node *next;
}
*head=NULL;
int main(){
int n,data;
printf("Enter the Number of Nodes\n");
scanf("%d",&n);
create(n);
print();
}
int create(int n){
int i=1,data;
struct node *temp=(struct node*)malloc(sizeof(struct node));
printf("Enter element %d:\n",i++);
scanf("%d",&data);
temp->data=data;
temp->next=NULL;
head=temp;
while(n-->1){
struct node *t=(struct node *)malloc(sizeof(struct node));
printf("Enter element %d:\n",i++);
scanf("%d",&data);
t->data=data;
t->next=NULL;
temp->next=t;
temp=t;
}
printf("Done :)\n");
}
void print(){
struct node *temp=head;
printf("Elements in list are:\n");
if(temp==NULL)
printf("List is Empty\n");
else
while(temp!=NULL){
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
现在,我了解大部分工作,但我想澄清一些混乱。
第一个节点创建为 head。第二个节点创建为 t,然后通过将 head 的下一个指向自身来连接到 head。 那么第三个节点如何知道我们将它连接到第二个节点(因为所有节点都命名为 t)。 是不是因为在 while 循环结束时temp = t
,所以在下一次运行时,新的 t 节点连接到前一个 t 节点的 temp。
如果是这种情况,那么我假设只有地址相互连接。
更准确地说,使用 malloc 我们分配一个data
内存,然后在 temp (它是指向节点的指针) next
,然后将第一个元素放在data
,将 NULL 放在next
,这就是我们的第一个节点。 之后,我们有一个指向第一个节点的头指针。
我真正的困惑是正在发生的事情是我们在每次循环运行时创建新的地址串,并且print()
使用这些地址从头到最后一个节点进行迭代。 并且exept head
在我们退出函数后没有任何东西可以访问我们的链表。
正确的?
术语可能不是重点。
是不是因为在 while 循环结束时 temp = t,所以在下一次运行时,新的 t 节点连接到前一个 t 节点的 temp。
是的。 temp
跟踪最新的节点。
struct node *next
保存下一个节点的内存位置。
在我们退出函数后,除了 head 没有任何东西可以访问我们的链表。
是的。 不知道head
,您将无法浏览您的列表。
第三个节点通过语句 temp->next=t 连接到第二个节点(temp 的地址为第二个,'t' 是一个新节点),最后,你正在使 temp=t 所以在下一次迭代中,temp将有第三个节点地址等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.