# Why does `length - 2` recursively give you the center of a linked list?

I am reading through an Algorithms book and am working through a recursive solution to the following question:

Implement a function to check if a linked list is a palindrome

This is an easy enough task, but the book suggests a recursive solution that I can't seem to wrap my head around. It states that to know when we are at the center of the linked list, we can perform the following operation:

``````recurse(Node n, int length) {
if (length == 0 || length == 1) {
return [something]; // At middle
}
recurse(n.next, length - 2);
...
}
``````

Why does `length - 2` recursively get you to the middle? Can someone explain this in detail? I understand that it works, but not mathematically why it works.

• the code snippet looks syntactically incorrect, have you tried to run / debug it? or at least to compile. See also How to ask “how to understand some code” questions – gnat Sep 21 '15 at 19:52
• The code is copied from the book. I am asking why it works mathematically, I am not looking to change it. – ApathyBear Sep 21 '15 at 19:55
• I think this is more "how does this algorithm work" than "how does this code work". The difference is subtle, but I would answer this one on a whiteboard if asked this question at work. I think that makes it fair game for Programmers over SO. – Stephen Sep 22 '15 at 0:01
• That's bad code. Convert it to tail-recursive to avoid blowing the stack, and it looks like it would probably still O(n²), which is bad... – Deduplicator Feb 6 '18 at 17:43

If you advance one step and subtract two from the length, you get a new sublist with the ends removed. Observe that the code does not just subtract from the length. It starts the sublist at `n.next`.