Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you would like to avoid using an external library, you may implement a linked list for your code. Although you may have to rewrite other parts of your program, it is an efficient way to handle dynamically growing memory in C++. I believe that std library provides <a href="http://www.cplusplus.com/reference/list/list/" rel="nofollow">templates</a> for creating these structures. If you would otherwise like to implement them yourself, here's some snippets to get your started:</p> <p>The structure:</p> <pre><code>struct PointNode { int point; PointNode * next; }; </code></pre> <p>Adding data:</p> <pre><code>void addPoint( PointNode ** head, int point ){ PointNode * temp = new PointNode; temp-&gt;point = point; temp-&gt;next = * head; * head = temp; } </code></pre> <p>Freeing memory:</p> <pre><code>void freeNodes( PointNode * head ){ PointNode * temp; while( head ){ temp = head-&gt;next; delete head; head = temp; } } </code></pre> <p>When you need to use the data as an array:</p> <pre><code>int getPoints( PointNode * head, int ** points ){ PointNode * temp = head; int i = 0; for( ; temp; temp = temp-&gt;next, i++ ); ( * points ) = new int[ i ]; for( i = 0, temp = head; temp; temp= temp-&gt;next, i++ ){ ( * points )[ i ] = temp-&gt;point; } return i; } </code></pre> <p>Example:</p> <pre><code>int main( ){ PointNode * head = 0; // make sure the head is always initialized to zero addPoint( &amp;head, 4 ); addPoint( &amp;head, 5 ); addPoint( &amp;head, -4 ); int * points; int len = getPoints( head, &amp;points ); for( int i = 0; i &lt; len; i++ ) cout &lt;&lt; points[ i ] &lt;&lt; endl; delete points; freeNodes( head ); return 0; } </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