[Solved] C++ linked lists read access violation


  • You havn’t deleted head & tail.
  • Assuming tail is the last, there is somewhere a node::next pointing to it, and you didn’t changed it to point to temp
  • What if the list is empty? you didn’t checked if head or tail is null.

Edit added fixed method

void swap_first_and_last() 
{
    //if there is less than 2 nodes - finished.
    if(!head || !tail || head==tail) return; 
    node *temp = new node;
    node *temp2 = new node;
    node *temp3;

    temp->data = head->data;
    temp->next = NULL;

    temp2->next = head->next;
    temp2->data = tail->data;

    temp3 = head;
    head = temp2;
    delete temp3; //delete old head
    temp3 = tail;
    //find the tail previous
    for(tail=head; tail->next!=temp3;tail=tail->next);
    //make tail previous point to tail
    tail->next = temp;
    tail = temp;//now it will point to new tail...
    delete temp3;//delete old tail
}

A better solution:

void swap_first_and_last() 
{
    node *temp;
    //if there is less than 2 nodes - finished.
    if(!head || !tail || head==tail) return; 
    for(temp=head; temp->next!=tail;temp=temp->next);
    temp->next = head; //set tail precedor's next to point to head, prepere for head = tail
    tail->next = head->next; //set tail's next to point head->next, prepere for head = tail 
    head = tail; //set tail as head
    tail = temp->next; //set old head as tail
    tail->next = NULL; // tail next is always null (was point to the 2nd).
}

1

solved C++ linked lists read access violation