Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double linked list adding elements to Head

I am trying to make a double linked list and there are 2 functions: First adds element to tail and second is supposed to add element right at the beggining but it does not work.

void AddNodeEnd (char addData)
    {
        nodePtr NewNode = new node;
        NewNode->next = NULL;
        NewNode->data = addData;


        if (head != NULL)
        {
            curr = head;
            while(curr->next != NULL)
            {
                curr = curr->next;
            }
            curr->next = NewNode;
        }
        else
        {
            head = NewNode;
        }
    }
    void AddNodeHead (char addData)
    {
        nodePtr NewNode = new node;
        NewNode->prev = NULL;
        NewNode->data = addData;

        head->prev = NewNode;
        NewNode->next = head;
        NewNode->prev = NULL;
    }
like image 921
AlexMIEL Avatar asked Jun 26 '26 20:06

AlexMIEL


1 Answers

I assume that head is a pointer to the first element of the list.

If you add a new node at the head of a list, the new node becomes the head. So if you added your element at the head of the list you have to assign at the end: head = newNode.

void AddNodeHead (char addData)
{
    nodePtr NewNode = new node;
    NewNode->prev = NULL;
    NewNode->data = addData;

    if ( head != NULL )     // consider an empty list
      head->prev = NewNode;
    NewNode->next = head;   // this also works for an empty list
    head = newNode;         // <- this is missing in your code
}
like image 134
Rabbid76 Avatar answered Jun 29 '26 10:06

Rabbid76



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!