http://ideone.com/OHyWS So I've managed to implement a really basic singly-linked list in C, as well as a few really basic functions to manipulate such a singly-linked list. Can anyone critique my code? What could be done in a better way?
You can design the list primitives (tune them) when you know what the use of them will be. For example, if you manage the list with *two* pointers (one to the beginning node, and one to the ending node, you don't have to loop over the whole list to find the end to do the append. So, operations at the end of the list are made *much* quicker. I call the two pointers that manage the list a *list control block*. You can get creative with the definition of the LCB for an empty list.
It's a good idea to *always* initialize a new node's link field, at least. I'd set the new node's link field to NULL. It's probably a good idea to set the data field to something as well. One of the really good ideas in C++ is the constructor, which you have to write for every object - it's a great way to remind you to do this. And it's better to initialize the node in just *one* place.
I like declaring my data types earlier in the program than you did. You position is good, in that you don't declare your struct until you need it, because the range() function doesn't need it. I like being able to look at the front of the file and see the data structures, because they're such important information. Thinking further, I would put the struct and prototypes for the functions into a header file. The client programs which use your linked list will need to be able to define one. And the header file should be included in the linked-list code that you show. When you do this, you assure that the compiler will generate the proper calling sequence for each function call. I like very much that you've carefully shown the type of each function's returned value. Do you intend for the linked-list clients to call range()? If not, it should be marked 'static'. I like to have a comment header before each function which says what it is good for. In small functions like these, the header comments are all you need. I don't know what your range() function is supposed to do without looking at all of its calls.
I'm new to linked lists, and so I like your idea of having a head and tail pointer for all singly-linked lists to speed-up things. For initializing nodes, might just make a function that creates a new one from the heap, initializes some values, and then returns a pointer. The range function just creates an array of size N of number from 0 to N-1 in ascending order (similar to the range() function in Python), I'm commenting the code I paste online from now on :-D
I like your idea of a specific function to initialize each data type a lot.
Join our real-time social learning platform and learn together with your friends!