swapList() and operator=() functions in a LinkedList class keep crashing in C++

119 Views Asked by At

I need a swapList(LinkedList& Other) function in charge of basically swapping the values of two lists. Currently, it takes the last element of Other and inputs it into the first element of *this. Then it also moves the last element of Other to the front of its list. Here's what I have so far:

      Node *nodePtr = Other.head;
      Node *temp = this->head;
      while(nodePtr){
        temp->value = nodePtr->value;
        nodePtr->value = Other.head->value;
        Other.head->value = temp->value;
        nodePtr = nodePtr->next;
      }
    }

Now, I know of the copy-swap idiom which I believe means I can just call the swap function in the operator=() overload. I just can't seem to figure out the swap. I've played with it a bunch and this is neither my first, nor my last iteration of the function. Any help is much appreciated. Searches just yield swapping nodes in a single list.

1

There are 1 best solutions below

0
On

Whenever playing with linked lists (or other linked structures), it is a really good idea to get out some paper and a pencil and draw your list, using boxes for values and arrows for pointers, and then use your eraser and new arrows to perform a swap on the paper.

You have to do it such that you never erase an arrow without first adding a new arrow to the target box/value.

Pay special attention to the possibility that the items being swapped are adjacent to each other!

Once you have that figured out you need to write your code to do the same thing in the same order.