繁体   English   中英

不明白为什么 head = head->next 有效

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM