This is not my code. I took this code off this website:
http://www.macs.hw.ac.uk/~rjp/Coursewww/Cwww/linklist.html
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.
#include<stdlib.h>
#include<stdio.h>
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<=10;i++) {
curr = (item *)malloc(sizeof(item));
curr->val = i;
curr->next = head; //2
head = curr; //3
}
curr = head; // 4
while(curr) { //5
printf("%d\n", curr->val);
curr = curr->next ;
}
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.
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.
head = curr → Why are we setting it equal to curr?
curr = head → and then setting curr = head after the loop is done.
while(curr) → Just to make sure, this is traversing through the list and it is equivalent to while(curr != NULL) right?