Implementing a Singly Linked-List in C
Over the past couple of days I have become very interested in brushing up on my limited C knowledge. As I discussed in my previous post on using the XOR swap method, everyday languages are becoming very high-level, and as a result taking away some of the fun. In the next couple of posts I wish to implement some of the common place data-structures found in development, but unlike previous attempts, these will be in straight C. The first such data-structure I wish to discuss is the common place singly linear linked-list.
As you can see from the implementation above, both insertion and removal methods allow the user to specify if they wish to effect the head or tail. Surprisingly, it was not until the ISO-C99 standard that C got a native boolean data type (_Bool). The ‘stdbool.h’ header file defines library macros (true, false) which resolve to the _Bool type. With the above implementation we are also able to print out the contents of the full linked-list at that present time.
The above method bootstraps the implementation together, providing us with an example of inserting items initially at the tail and then at the head. We then delete four items from the list, in a similar manner to the insertion step, deleting half from the tail and the other half from the head.
We can then use the command above, which simply compiles the file and subsequently executes it.