-
Code:
BEN10, i explicitly let know that actually it returns pointer to my struct type.
Just to second BEN10, my observation would be that most people do not cast malloc and it is not necessary. The pointer type will be set by the left hand side of the assignment.
Today's code looks much closer to the norm, I notice you are using the return pointers which IMO is the best way to go. A couple of minor things from removenode():
Code:
//handle the deletion of first element
if (list->ptr != NULL && list->data == value)
{
first = list->ptr;
list->ptr = NULL;
free(list);
return first;
}
It's sort of pointless to set list->ptr to NULL there since it is part of a struct that is about to be free'd anyway. A good rule with pointer when you free them is to then set them NULL, but only if you are keeping the handle in a variable that might get reused. But after free(list), it will be impossible to make use of list->ptr.
You could nest the two blocks dealing with first matching value:
Code:
if (list->data == value) {
if (!list->ptr) { /* the only element */
free(list);
return NULL;
} else { /* the first element */
first = list->ptr;
free(list);
return first;
}
}
Which will be a slight optimization since in the case of deleting the first element, we only need to check those (binary/boolean) conditions (value and ->ptr) once each instead of checking list->ptr twice and then value.
Code:
while (list->ptr != NULL)
if you make this "while (list)" you can include deleting the last pointer in this loop and not need a seperate block afterward. If none of the nodes match, list will finally get assigned NULL because the last list->ptr is/should be NULL, and the loop will end.
But generally a good job methinks.
-
excellent, that optimization makes sense, thank you very much :D
but one question about linked lists... how often do you really need such stuff? i'm mostly into electronics than programming now..
it is just interesting for me how really good it is... for example in some big sophisticated program...so many number of allocation and freeing the memory...is it efficient?
how about stack? do you think implementing a stack with a linked lists is a good idea?
how often have u ever had to implement linked list to solve real problem, rather than for educational purposes?
-
[QUOTE=BlackOps;877659]how about stack? do you think implementing a stack with a linked lists is a good idea?
[QUOTE]
I'm also very new to datastructure, so I can't tell about your other doubts. But about linked implementation of stacks, it has more advantages than array implementation. No space is pre allocated to a stack and that's why no stack uses more space than it needs. Also more than one stack can be implemented from the single available list. The disadvantage of the array implementation is that not exact number of nodes can be determined at the compile time, thus there's always a possibility that the size we allocated becomes insufficient.