4 ms·
I think the main lesson that's there, is that in edge cases, it is sometimes helpful to work with pointers which point to the structures you're actually working
by kutkloon7 10y ago
I think the main lesson that's there, is that in edge cases, it is sometimes helpful to work with pointers which point to the structures you're actually working with, instead of considering the structures themselves. This especially seems to work for getting rid of null checks.
This takes some getting used to, but it allows you to write more efficient code. I would do this in kernel development (smart people, high demands on performance), but I would not recommend to write code like this is enterprise software.
When you zoom out a bit, and describe the task with natural language, you can also see that this might be a good idea: "Find the node that is equal to entry, then, if the previous node exists, set the 'next' pointer of the previous node to the 'next' pointer of the current node." sounds a lot more tedious than "Find the pointer that points to entry, and set it to the 'next' pointer of entry.".
This also works for more complicated tasks:
// removes all instances from the linked list and return the number of entries removed
int removeentries(valuetoremove, list)
{
removedentries = 0; // how many entries we've removed
prevpt = NULL; // pointer to previous
entrypt = list.head; // get pointer to first node
// walk the list (be careful, head can be a nullpointer)
while (entrypt) {
if (*entrypt == valuetoremove)
if (prevpt) {
prevpt->next = entrypt->next;
removedentries++;
}
prevpt = entrypt; // save current node as prev for next node
entrypt = entrypt->next; // move to next node
}
return removedentries;
}
can be re-written to:
int removeentries(valuetoremove)
{
removedentries = 0; // how many entries we've removed
indirect = &head; // points to the current node
// walk the list
while (indirect) {
// remove current entry from list if its value equals valuetoremove
if (indirect->value == valuetoremove) {
*indirect = *indirect->nextpt;
removedentries++;
}
indirect = indirect->nextpt;
}
return removedentries;
}