Note that there are some explanatory texts on larger screens.

plurals
  1. POExplanation of code (linked list C)
    primarykey
    data
    text
    <p>This is not my code. I took this code off this website: </p> <p><a href="http://www.macs.hw.ac.uk/~rjp/Coursewww/Cwww/linklist.html">http://www.macs.hw.ac.uk/~rjp/Coursewww/Cwww/linklist.html</a></p> <p>I am using for reference material on how to build a linked list. I'm a little confused on what is going on. Can someone please explain to me what is going on. I'll mark what is confusing me with 1-5.</p> <pre><code>#include&lt;stdlib.h&gt; #include&lt;stdio.h&gt; struct list_el { int val; struct list_el * next; }; typedef struct list_el item; void main() { item * curr, * head; int i; head = NULL; //1 for(i=1;i&lt;=10;i++) { curr = (item *)malloc(sizeof(item)); curr-&gt;val = i; curr-&gt;next = head; //2 head = curr; //3 } curr = head; // 4 while(curr) { //5 printf("%d\n", curr-&gt;val); curr = curr-&gt;next ; } </code></pre> <ol> <li><p>head = NULL → why is head being set to NULL? I know that you are supposed to (I do it out of habit) but I don't really know why.</p></li> <li><p>curr->next = head → I never really understood this as well. Maybe I have my definition of "head" wrong but in a regular linked list, is it the starting node or the last node on the list? I've always assumed it was the starting node but in this line it looks like it's the last node.</p></li> <li><p>head = curr → Why are we setting it equal to curr?</p></li> <li><p>curr = head → and then setting curr = head after the loop is done.</p></li> <li><p>while(curr) → Just to make sure, this is traversing through the list and it is equivalent to while(curr != NULL) right?</p></li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    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