Vaibhav Sundriyal
Vaibhav Sundriyal

Reputation: 577

Doubly Linked List Pointer Confusion

Below is the code for inserting a node in a doubly linked list.

struct dllist
{
    int data;
    struct dllist *prev, *next;
};


void DLLInsert(struct dllist **head, int position, int data)
{
    int k = 1;
    struct dllist *temp, *newNode;
    newNode = (struct dllist *)malloc(sizeof(struct dllist));
    if (!newNode)
    {
        printf("Memory Error\n");
    }
    newNode->data = data;
    if (position == 1)
    {
        newNode->next = *head;
        newNode->prev = NULL;
        *head = newNode;
        return;
    }
    else
    {
        temp = *head;
        while (temp->next != NULL && k < position - 1)
        {
            k++;
            temp = temp->next;
        }
        if (temp->next == NULL)
        {
            temp->next = newNode;
            newNode->prev = temp;
            newNode->next = NULL;
        }
        else
        {
            newNode->prev = temp;
            newNode->next = temp->next;
            temp->next = newNode;
            temp->next->prev = newNode;
        }
    }
}

I am getting somewhat confused in the underlying pointer operations being a newbie. A **head is passed onto the function to modify it. But in case when the position>1, a copy of *head(temp) is used to modify the list compared to the case when position==1. Can anybody explain me why is it so?

Thanks

Upvotes: 0

Views: 107

Answers (2)

SethB
SethB

Reputation: 2090

In the case of position==1, your new element will become the new head. You already know exactly where it is. Otherwise, you need to find the position.

temp = *head;
        while (temp->next != NULL && k < position - 1)

This is used to iterate through the list until you find the element in the position you are going to insert at.

    temp = temp->next;

The first element you assign to temp is head, but it is replaced with the next element in each iteration.

Upvotes: 1

irrelephant
irrelephant

Reputation: 4111

When position > 1, temp is set to *head, and the code iterates temp through the linked list to the node at index position. Effectively, you are modifying the node at index position.

When position = 1, you are modifying the head node, so you don't need to iterate.

Upvotes: 1

Related Questions