Search code examples
ccircular-list

adding node to the beginning of double circular linked list in c


I am trying to add 'n' number of nodes to the beginning of double circular linked list here is the function for adding the node:

//the **head is assigned the address of the original head pointer which is being passed from the main function.

void insert(struct node**head,int n){
 while(n-- >0){
    int num;
    //to input the data for the linked list
    scanf("%d",&num);
    struct node* newnode=(struct node*)malloc(sizeof(struct node));
    newnode->data=num;

    if(*head==NULL){
        newnode->next=newnode;
        newnode->prev=newnode;

        *head=newnode;
    }
    else{

        newnode->next=*head;
        newnode->prev=(*head)->prev;

        //to make the previously first node point to the new first node
        newnode->next->prev=newnode;
        //to make the last node point to the new first node
        (*head)->prev->next=newnode;
        *head=newnode;

    }
 }
}

when I execute it, it is not showing any ouput but when I change

//to make the last node point to the new first node
            (*head)->prev->next=newnode;

this line to

newnode->prev->next=newnode;

the code is running. I am not able to understand what is the difference between the two statement.


Solution

  • (*head)->prev->next=newnode;
    ...
    newnode->prev->next=newnode;
    

    I am not able to understand what is the difference between the two statement.

    newnode->prev has been correctly set to the node before the head. In contrast, (*head)->prev at this time has already been altered by newnode->next->prev=newnode, since newnode->next=*head. Hence (*head)->prev no longer points to the node before the head, but to the new node. That's the difference.