Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The code looks fine, but I would suggest a minor change to your <code>while</code> condition</p> <pre><code>while(prevNode != currentNode &amp;&amp; prevNode != NULL) </code></pre> <p>For two reasons</p> <ul> <li>Your code, as currently stated, could stop if the node we are looking for is pointed to by either <code>prevNode</code> or <code>prevNode-&gt;link</code> (and therefore we will have no idea which particular one of the two points to <code>currentNode</code> -- if we wanted to know, we would have to check with an <code>if</code> condition). With the change above, the target node is guaranteed to be stored in <code>prevNode</code> (if at all -- see next point). </li> <li>For safety's sake, it would be good to check that <code>prevNode</code> is not <code>NULL</code>. However, as Pavel mentions, this test is unnecessary if <code>currentNode</code> is guaranteed to be in the list.</li> </ul> <hr> <p><strong>Edit in response to comment</strong></p> <p>Given that you don't need to know whether <code>currentNode</code> is in <code>prevNode</code> or <code>prevNode-&gt;link</code>, and since you want to stop (if possible) on <code>currentNode == prevNode-&gt;link</code>, then your original <code>while</code> is fine. However...</p> <blockquote> <p>there is an if statement higher up in the code that prevents <code>prevNode</code> from being null already</p> </blockquote> <p>It seems like you're missing the point of why you should check for <code>NULL</code>. Yes, that's good you check it before, but the reason why we have the <code>NULL</code> check in the loop is in the case where <code>currentNode</code> is <em>not</em> in the list, so you eventually reach the last node. Presumably (if you do this like most other linked lists) the value of <code>link</code> for your last node is <code>NULL</code>. If so, your current code will eventually end up calling <code>NULL-&gt;link</code> which of course will crash your program. That's why you should still check for <code>NULL</code></p> <pre><code>while(prevNode != NULL &amp;&amp; prevNode != currentNode &amp;&amp; prevNode-&gt;link!=currentNode) </code></pre> <p>If you're <em>absolutely sure</em> that <code>currentNode</code> will be in the list, then I <em>guess</em> that check is also unnecessary, but it really is a good habit to get into.</p>
 

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