Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Linked lists are templates allowing any type of variable to sit in them. In my honest opinion, you'd be best off using the <code>std::list</code> which requires the <code>#include &lt;list&gt;</code> header file.</p> <p>Of course, if you really want the experience of writing a linked list class yourself then the following code makes a deep copy of a list:</p> <pre><code>List::List( const List&amp; other) { if( other.head_ != nullptr) { head_ = new Node( other.head_-&gt;item_); // copy first node assert( head_ != nullptr); // ensure that the memory was allocated correctly // copy the rest of the list Node* pnew = head_; // loop through the list until you reach the end (i.e. a node that's nullptr) for( Node* porig( other.head_-&gt;next_); porig != nullptr; porig = porig-&gt;next_) { // assign the next node in the destination list to the next node in the paramter's list pnew-&gt;next_ = new Node( porig-&gt;item_); assert( pnew-&gt;next_ != nullptr); // ensure that the memory was allocated correctly pnew = pnew-&gt;next_; // move onto the newly created node in the destination list } } else // if the parameter is empty then the destination list will be empty as well head_ = nullptr; } </code></pre> <p>As for the destructor, you just need to run through the list deleting the nodes as you go:</p> <pre><code>List::~List() { while( head_ != nullptr) { // keep looping until the list gets to the end // make a second pointer to the node you are about to delete (so you don't lose track of it) Node* pn( head_); // move the head_ onto the next node essentially "removing" the first node from your list head_ = head_-&gt;next_; // delete the node that you've just "removed" from your list delete pn; } } </code></pre> <p>I've tried to make the comments clear up anything that might be unclear.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload