3 ms·
I think what's missing in the mental model of the elegant solution is, that the IntList-pointer does not point to a complete list or an element of the list, but
by maweki 6y ago
I think what's missing in the mental model of the elegant solution is, that the IntList-pointer does not point to a complete list or an element of the list, but to a tail of some list (that might be the complete list). This explains why the head is not really a special case, as it points to the tail that is complete. And you can just exchange a tail.
So I think the image with the blue boxes is misleading and it should be
->[4->[12->[3->[6->[2->[]]]]]]
It is now obvious that you can always point -> to a different [...]
And as it turns out, that is basically the Cons/Nil view of a list from functional programming or lisp, if you're so inclined. And in those languages you would pattern match on the constructor once and do the tail-recursive call.
- dhanna 6y agoRight, I think the key insight is that the special case is simply unnecessary if you have the abstract model of the data structure correct. A linkedlist is just x::xs. The c code being weird is more of an implementation detail that shouldn’t be of much focus.