[英]couldn't understand why head = head->next works
我不知道为什么head = head->next
在我们没有存储任何内容或在head->next
中存储NULL
时起作用
这是两个功能
第一个 function 采用int
类型的参数n
并在此 function 中创建列表,我们定义head->next = NULL
第二个 function 即deletefirstnode
删除第一个节点,但在此 function head->next
确实有效并指向列表中的另一个节点,我们使用temp->next
访问下一个节点,但为什么在这种情况下head->next
请有人为我解释一下
void createlist(int n){
struct node *newnode, *temp;
int data, i;
head = (struct node*)malloc(sizeof(struct node));
if(head == NULL){
printf("unable to allocate memory");
}
else{
printf("enter the data of node 1 : ");
scanf("%d", &data);
head->data = data;
head->next = NULL;// here is where we define head->next to NULL
temp = head;
for(i=2; i<=n; i++){
newnode = (struct node*)malloc(sizeof(struct node));
if(newnode == NULL){
printf("unble to allocate memory");
}
else{
printf("enter the data of node %d", i);
scanf("%d", &data);
newnode->data = data;
newnode->next = NULL;
temp->next = newnode;
temp = temp->next;
}
}
printf("singly linked list created successfully\n");
}
}
void deletefirstnode(){
struct node *todelete;
if(head == NULL){
printf("list is already empty");
}
else{
todelete = head;
head = head->next;//and why this works now I am confused
printf("\ndata deleted = %d\n", todelete->data);
free(todelete);
printf("successfully deleted the first node from list\n");
}
}
在您的程序 head 中,您尚未将 head 全局声明为NULL
,因此head
指向您之前使用head
的链表中的某个位置。 如果head->next
不是NULL
那么你的单链表将没有尽头。 而对于删除,即
todelete = head;
head = head->next;
free(todelete)
todelete
存储head
的地址,然后将head
指向next,以切断当前head
的链接并将其指向下一个地址,否则要删除的节点将保留在memory中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.