Linked List Operator+ Overloading Question

Hi all,

I have written an operator+ overload function for a linked list queue implementation, but I was wondering if it makes a difference/is better to use new_queue = *this; to copy the left operand, instead of looping through the left operand and enqueueing its contents to the new queue (similar to what is done with the right_hand_side, except the pointer associated with the left side is the member variable front_ptr_). Here is my code down below. Thanks in advance!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
template<class ItemType>
LinkedQueue<ItemType> LinkedQueue<ItemType>::operator+(const LinkedQueue<ItemType> &right_hand_side) const {
    
    LinkedQueue<ItemType> new_queue; //new empty list

  // If this queue is empty return the other one.
    if (IsEmpty()) return right_hand_side;

  // ADD CODE HERE.

  // A. Add the nodes from this queue to new_queue.
      new_queue = *this; //is this better?
    
  // B. Continue adding nodes from the right_hand_side queue to new_queue.
      Node<ItemType>* right_chain = right_hand_side.front_ptr_;

   //I originally had while (right_chain != nullptr) as the condition
    while (right_chain != right_hand_side.back_ptr_) { 
        new_queue.Enqueue(right_chain->GetItem());
        right_chain = right_chain->GetNext();
      }//end while
    //newly added
   //if right_chain points to last node and queue is not empty.
    if (right_chain == right_hand_side.back_ptr_ && !right_hand_side.IsEmpty()) {
        new_queue.Enqueue(right_chain->GetItem()); //add last item to queue
    }
  // END ADD CODE.
  // Add this queue.
    return new_queue;
}//end operator+  
Last edited on
instead of looping through the left operand and enqueueing its contents to the new queue
This needs to be done anyway.

if your operator=(...) does the deep copy then you should use it as you did otherwise it'd be wrong.

I originally had while (right_chain != nullptr) as the condition
And why did you change that?
Topic archived. No new replies allowed.