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;
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With