Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Please look at this <em>very</em> carefully:</p> <pre><code>template &lt;class Type&gt; Type LinkList&lt;Type&gt;::GetItem(int itemNumber) const { Node&lt;Type&gt;* cursor = NULL; // loop over all items in the linked list for(cursor = first; cursor != NULL; cursor = (cursor -&gt; next)) { // for each item in the linked list, run a for-loop // counter from 0 to (used-1). for(int i = 0; i &lt; used; i++) { // if the passed in itemNumber matches 'i' anytime // before we reach the end of the for-loop, return // whatever the current cursor is. if(itemNumber == i) { return(cursor -&gt; data); } } } } </code></pre> <p>You're not walking the cursor down the list <code>itemNumber</code> times. The very first item <code>cursor</code> references will kick off the inner-for-loop. The moment that loop index reaches itemNumber you return. <strong>You never advance your cursor if the linked list has at least <code>itemNumber</code> items in the list.</strong>. In fact, the two of them (cursor and itemNumber) are entirely unrelated in your implementation of this function. And to really add irony, since <code>used</code> and <code>cursor</code> are entirely unrelated, if <code>used</code> is ever <strong>less</strong> than <code>itemNumber</code>, it will ALWAYS be so, since <code>used</code> doesn't change when <code>cursor</code> advances through the outer loop. Thus <code>cursor</code> eventually becomes NULL and the results of this function are undefined (no return value). In summary, as written you will always either return the first item (if <code>itemNumber &lt; used</code>), or undefined behavior since you have no return value.</p> <p>I believe you need something like the following instead:</p> <pre><code>template&lt; class Type &gt; Type LinkList&lt;Type&gt;::GetItem(int itemNumber) const { const Node&lt;Type&gt;* cursor = first; while (cursor &amp;&amp; itemNumber-- &gt; 0) cursor = cursor-&gt;next; if (cursor) return cursor-&gt;data; // note: this is here because you're definition is to return // an item COPY. This case would be better off returning a // `const Type*` instead, which would at least allow you to // communicate to the caller that there was no item at the // proposed index (because the list is undersized) and return // NULL, which the caller could check. return Type(); } </code></pre>
    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.
 

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