Total size of a linked list in C
c, linked-list
Solution
You usually go through the list until you reach the tail item while counting in the meanwhile, code should be something like that:
int listLength(struct Data_Struct* item)
{
struct Data_Struct* cur = item;
int size = 0;
while (cur != null)
{
++size;
cur = cur->Next;
}
return size;
}
Mind that complexity of this operation is linear with the size of the list, so it's O(n) and it's quite inefficient. You could store size somewhere and update with list insertions and deletes to avoid any overhead and being able to calculate it in a constant time O(1).
EDIT: Didn't notice you wanted size of the whole data included into the list. In your case you can keep the same approach used for calculating the length but instead that adding 1 for every element you should add the total length of strings:
size += strlen(Name)+strlen(Task)+strlen(Pos);
Mind that since data inside your list element if of type `char*` the effective size of the `Data_Struct` is just 4 pointers, that's why you need to use a support function like `strlen`, otherwise you can't get real dimension of the strings.
Which is the difference?
sizeof(Data_Struct) == 16
because the `Data_Struct` type contains 4 pointers, three for pointers to char and one for the next element in the list
sizeof(Name) == sizeof(Task) == sizeof(Pos) == 4
because these variables are of type pointer to char, so they are pointer, no concrete value, and it's usually 4 bytes (I'm assuming a 32 bit architecture)
strlen(Name) == length in chars of the string
because the function works exactly to calculate the length of a string.
Problem
Alright... my Introduction to Data Structures from CS is so rusty I need to ask this here. I have a linked list whose structure is: ``` struct Data_Struct { char *Name; char *Task; char *Pos; struct Data_Struct *Next; }; typedef struct Data_Struct MyData; ``` Now, at some point in my application I filled the list with data. The question is, how do I get the total size of the data stored in there? How many chars are there? Something like ``` sizeof(MyData); ``` That will return the size of the info stored in the list. code is appreciated. Thanks! EDIT: Unfortunately this is NOT homework. I finished school more than 20 years ago and frankly i never ever had to use linked lists on anything. I just don't remember. What I am doing is iterate the list and get the strlen() of each element and keep it on a global size but I wanted to know if there was a better way. and NO, I don't need the size of the linked likes (the count of nodes), i just want to know how many characters are stored in there. thanks