【问题标题】:couldn't understand why head = head->next works不明白为什么 head = head->next 有效
【发布时间】:2020-07-14 14:38:59
【问题描述】:

我不知道为什么 head = head->next 在我们没有存储任何内容或 NULLhead->next 中时有效

这是两个函数
第一个函数采用int 类型的参数n 并在此函数中创建列表,我们定义为head->next = NULL

第二个函数,即deletefirstnode删除第一个节点,但在这个函数中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-&gt;next; - 为指针赋值。问问自己head 在赋值操作之前和之后指的是什么。不要用深刻的思想把它复杂化。说出最先想到的事情。然后,使用调试器单步执行您的程序,检查变量值,看看您是否正确。
  • headelse 的情况下不是NULL。因此,head-&gt;next 有效; head-&gt;next 可能指向一个有效地址或NULL。您询问的代码的目的是删除当前的head 并将下一行(如果有)提升为head
  • 指向和存储是完全不同的,我认为你在使用指针时应该更多地考虑指向而不是存储
  • 欢迎来到 SO。这类关于链表管理的问题最好从纸笔开始。在纸上画出节点应该很有用。
  • @Rahul Magar 解释为什么这个 head = head->next 在你看来不起作用。

标签: c data-structures linked-list null


【解决方案1】:

在您的程序头中,您没有将头全局声明为NULL,因此head 指向您之前使用过head 的链表中的某个位置。如果head-&gt;next 不是NULL,那么你的单链表将没有尽头。而对于删除,即

todelete = head;
head = head->next;
free(todelete)

todelete存储了head的地址,然后你把head指向next,这样就切断了head的当前链接,指向下一个地址,否则就是你要指向的节点删除将保留在内存中。

【讨论】:

    猜你喜欢
    • 2019-09-03
    • 1970-01-01
    • 2011-01-14
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多