c-制作链表时的混乱

  • 本文关键字:混乱 链表 c 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 Nodesn");
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 Emptyn");
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,我们将datanext的内存分配给temp(它是指向节点的指针(,然后在data中放置第一个元素,在next中放置NULL,这就是我们的第一个节点。之后,我们有一个指向第一个节点的头指针。

我真正困惑的是,我们在每次循环运行时都会创建新的地址串,而print()使用这些地址从头到最后一个节点进行迭代和exepthead在我们退出函数后,没有任何东西可以访问我们的链表

正确吗

术语可能不切中要害。

第三个节点通过语句temp->连接到第二个节点;next=t(temp的地址为second,'t'是一个新节点(,最后,您将使temp=t,因此在下一次迭代中,temp将有第三个节点地址,依此类推

是因为while循环结束时temp=t,所以在下一次运行时,新的t节点连接到前一个t节点的temp。

是。temp跟踪最新的节点。

CCD_ 9保存下一个节点的存储器位置。

并且在我们退出函数后,除了head之外,没有任何东西可以访问我们的链表。

是。如果不了解head,您将无法浏览您的列表。

最新更新