简体   繁体   中英

couldn't understand why head = head->next works

I don't know why head = head->next works when we have stored nothing or NULL in the head->next

these are two functions
1st function is taking an argument n of int type and creates the list in this function we define that head->next = NULL

and second function ie deletefirstnode deletes first node but in this function head->next really works and points to another node in the list we use temp->next to access the next node but why in this case head->next
please somebody explain it for me

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");
    }
}

In your program head you have not globally declared head as NULL so head is pointing to somewhere in the linked list in which you have previously used head . If head->next had not been NULL then your Singly Linked List will have no end. And for the delete,ie,

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

todelete stores the address of the head and then you point your head to next so as to cut the current link of head and point it to the next address,otherwise the node which you want to delete will remain in the memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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