0

I'm using this struct:

struct node
{
    T data;
    node *next;
};

node *head;
node *headCopy;

to create a single linked list based on the implementation of a stack. All of my core stack methods are working. I am just having trouble implementing the copy constructor which takes arguments:

LinkedStack<T>::LinkedStack(const LinkedStack<T>& aStack) 

What I currently have is this (which isn't working):

node *temp;
temp = head;
while (temp != NULL)
{
    headCopy = head;
    temp = temp->next;
}

I suppose that : my biggest problem is I am having trouble visualizing how this copy will happen. I've looked at other examples, but I am unable to follow. I had no problem creating a copy constructor for an array based stack. I imagined it would be similar to my show() function except instead of outputting I am reassigning to another linked-list. My show() method is as follows:

node *temp;
temp = head;
while (temp != NULL)
{
    std::cout << temp->data << std::endl;
    temp = temp->next;
}

Any help would be appreciated, thank you!

acornagl
  • 521
  • 5
  • 24
Olivia
  • 51
  • 4

1 Answers1

1

For each node in the original you'll need to allocate a new node in the copy. Your question doesn't include enough details to spell out the exact code. You'll have roughly the following operations:

  1. Allocate a new object which will look something like

    node* n = new node();
    
  2. You'll need to assign the data from the original, i.e., something like

    n->data = temp->data;
    

    (unless your node has a constructor taking the data as argument in which case you can allocate it using new node(temp->data)).

  3. You'll need to like the new node n into the correct location.

If your stack class has a way to push a new element onto the end, you may be able to use that: instead of creating new nodes directly you'd run over the original in a loop and add the element to the end of the new list.

When defining a copy constructor remember to also define a copy assignment! The easiest way to do is to use the copy constructor to create the actual copy and then swap the content of the temporary object with the object assigned to.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380