Reputation: 399
While studying data structure I came up with the Linked List section, particularly the head node and tail node section.
From what I was read an taught, many users of C tend to use only Node *head;
.
But there was a part where using the following code was recommended to be used:
typedef structure _node node;
struct _node{
int data;
Node *next;
}
typedef structure list {
Node *head;
Node *tail;
int size;
} List;
As a person who has just started studying C and data structure, I found it more understandable when writing it like this, but since the teacher told us that most people do not write it like this but just use Node *head
, I was curious on knowing what others actually used in reality.
Do developers and C users really use just one line, or do they use it like the code written above?
Upvotes: 1
Views: 90
Reputation: 35154
The data structure depends on whether you want to optimise for specific use cases. For example, if you have a linked list, where the elements shall be inserted mostly before the first element, then it may be superfluous to maintain a tail
. If, however, elements shall be inserted mostly at the end, it makes sense to maintain a pointer to the tail instead of running through the complete list again and again whenever an element shall be inserted. And if you want to use your list for a First-In-First-Out (FIFO) use case, then it is beneficial to have both the head and the tail available directly, too.
Similarly, whether you store the size (redundantly) of the list might depend on how often you want to access that value. Since it can be calculated, you could derive the size on demand. If you access it rather often, or if you have long lists, then storing the value separately makes sense.
So it depends, and there may be other factors to consider as well.
Upvotes: 2