0

**following is my linked list code... its not working for some reason. Can someone help me out here?

void insertAtTheEnd(node *&head, int data){
    node *newNode= new node(data);
    newNode->data=data;
    node *temp=head;
    while(temp!=NULL){
        temp=temp->next;
    }
    temp->next=newNode;
    newNode->next=NULL;
    newNode->prev=temp->next;

}
  • 3
    You have a loop that says `while(temp!=NULL)`. What is `temp` after the loop has terminated? – n. m. could be an AI Mar 25 '21 at 08:12
  • Add `while(temp!=nullptr && temp->next!= nullptr)` as loop termination condition. and assign previous node for inserted node as `newNode->prev=temp`. Also you need to consider case when header is null – TruthSeeker Mar 25 '21 at 08:26

1 Answers1

0

As you have it coded, temp is guaranteed to be NULL when your while loop exits. Hence, temp->next=NULL will crash.

When you probe for a position in the list, you typically need to keep "previous" variable to point to the item before the one you are iterating with.

node* temp = head->next;
node* previous = head;

while (temp)
{
    previous = temp;
    temp = temp->next;
}
// when the while loop returns, `previous` is the last element in the list
previous->next = newNode;
newNode->prev = previous;
newNode->next = nullptr;

Another case you missing in your code. When head is NULL (empty list), you need to update head to be your newNode

// empty list - return the new node as head
if (head == nullptr)
{
    newNode->next = nullptr;
    newNode->prev = nullptr;
    head = newNode;
    return;
}
selbie
  • 100,020
  • 15
  • 103
  • 173
  • And if you want to get a little crazy, the previous pointer can be avoided with a [pointer-to-pointer trick like this one](https://stackoverflow.com/a/59779376/4581301). – user4581301 Mar 25 '21 at 08:21