[英]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.