Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Memory for new nodes has to come from <em>somwhere</em>. You can certainly create individual variables and link them manually:</p> <pre><code>link a, b, c; ... a.next = &amp;b; b.next = &amp;c; c.next = NULL; </code></pre> <p>As you can imagine, this approach doesn't scale; if you want more than 3 elements in your list, you'd have to allocate more than 3 <code>link</code> variables. Note that the following <em>won't</em> work:</p> <pre><code>void addToList( link *b ) { link new; ... b-&gt;next = &amp;new; } </code></pre> <p>because <code>new</code> <em>ceases to exist</em> when the <code>addToList</code> exits, so that pointer is no longer meaningful<sup>1</sup>.</p> <p>What you <em>can</em> do is use an array of <code>link</code> as your "heap", and allocate from that array. You'll need to keep track of which elements are available for use; an easy way of doing that is initializing the array so that each <code>a[i]</code> points to <code>a[i+1]</code> (except for the last element, which points to NULL), then have a pointer which points to the first available element. Something like the following:</p> <pre><code>// You really want your "heap" to have static storage duration static link a[HEAP_SIZE]; // Initialize the "heap" for ( size_t i = 0; i &lt; SIZE - 1; i++ ) a[i].next = &amp;a[i+1]; a[i].next = NULL; // Set up the freeList pointer; points to the first available element in a link *freeList = &amp;a[0]; // Get an element from the "heap" link *newNode = freeList; freeList = freeList-&gt;next; newNode-&gt;next = NULL; // Add a node back to the "heap" when you're done with it: deletedNode-&gt;next = freeList; freeList = deletedNode; </code></pre> <p>Again, you're limited in how many list nodes you can create, but this way you can create a large enough "heap" to satisfy your requirements. </p> <p><hr> <sup>1. Obviously, the phsyical memory location that <code>new</code> occupied still exists, but it's now free for other processes/threads to use, so the value contained in that address will no longer be what you expect.</sup></p>
    singulars
    1. This table or related slice is empty.
    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. VO
      singulars
      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