Create a linked list:
So we want to make a function that creates a linked list from scratch, something look like this:
sllnode* create(VALUE val);
Inside the bracket, (VALUE val) is the initial data value that this going to be put into the first element that we are creating for this linked list.
So it could look something like this:
sllnode* new = create(6); // So we are going to create a linked list, and put "6" into the 'val' field for the first member of the linked list that we will create.
And then this function returns a pointer "sllnode*" which tells you where is the start of this linked list. Because all we need to know is the start point, all members are linked, so once we know the start address then we can trace down to access all other members in this linked list.
sllnode* new = create(6); // So in this example, 'new' is the variable name for the pointer that we are going to return. When we write:" sllnode* new " that means 'new' is a pointer variable that is of the type 'sllnode*'.
So the steps that we need to do for creating a new linked list are:
a. Dynamically allocate a spece for a new sllnode.
So we use malloc() to allocate space for the first member of this linked list that we have created.
b. ofcourse when we use malloc() to allocate memory space we always need to check to make sure we didn't run out of memory. That means make sure the returned pointer is not NULL.
c. Initialize the node's val field. Like we put "6" into the value field of this first node.
d. Initialize the node's next field. In this case, we are creating the very first member of this linked list, so 'next' field shouldn't be pointing to anywhere. Therefor it should be "NULL". And we can see later on, when we insert new nodes into this linked list, we always insert it to the front of the previous one. So actually this very first node that we created will always be the last one in this list, and the 'next' field will always be "NULL".
e. Return a pointer to the newly created sllnode.
In this example we are returning the variable named 'new' which is a pointer of the 'sllnode*' type.