Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This code:</p> <pre><code>cursor = new Node; cursor = begin; </code></pre> <p>Does the following:</p> <ul> <li>Create a new Node object on the stack</li> <li>Put the address of that object in variable <code>current</code></li> <li>Immediately overwrite that address with the address that <code>begin</code> contains</li> </ul> <p>i.e. all it does is leak a new <code>Node</code>. <code>cursor</code> and <code>begin</code> point to the same thing after that.</p> <p>Thus the line:</p> <pre><code>cursor-&gt;next = begin; </code></pre> <p>Makes a loop. <code>cursor-&gt;next == begin == cursor</code>.</p> <p>Removing the <code>cursor = begin;</code> line, and returning cursor will do what you want. The Node created with <code>new Node</code> will be the new head of the list, and the one that <code>begin</code> pointed to at the start of the function will be the second node in that list.</p> <p>Now when you want to traverse (not add to) that list, you can do something like:</p> <pre><code> Node *cursor = begin; // assuming begin is the head of your list while (cursor != 0) { // process this node cursor = cursor-&gt;next; } </code></pre> <p>And that will visit each node in your list, assuming you've built it correctly.</p> <p>A few notes:</p> <ul> <li><p>The code that calls this function should probably look something like:</p> <pre><code>list = add_node(list, ...); </code></pre> <p>If you don't have that, you'll not get what you want.</p></li> <li><p>If the address you see in <code>begin</code> looks <em>very</em> different from the one returned by <code>new</code>, you're could be doing something wrong, i.e. <code>begin</code> could point at a stack address. Don't put objects from your stack on the list, make sure you all allocate them with <code>new</code>. (If <code>begin</code> points to a global static variable, that's fine - but make sure you don't <code>delete</code> it).</p></li> <li><p>Unless you actually <em>need</em> a dummy node, I'd suggest you remove that too - it makes your <code>add_node</code> function more complex than it needs to be.</p></li> </ul> <p>Here's a skeleton of how you would do it without that special dummy node (incomplete code):</p> <pre><code>Node *add_node(Node *list, ...) { Node *new_node = new Node; new_node-&gt;next = list; // fill in other properties return new_node; } </code></pre> <p>And to use this:</p> <pre><code>int foo() { Node *list = 0; // or nullptr for C++11 list = add_node(list, ...); // add item 1 list = add_node(list, ...); // add item 2 list = add_node(list, ...); // add item 3 ... </code></pre>
 

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