We will be adding the ‘retrieve’ method which will take an integer as a parameter. If the integer is positive it will return an element counted from the head of the list. If the integer is negative it will retrieve the element counted from the tail of the list. Our first test will be the following.
With tests in the Red we need to modify the SLL so that they turn Green. While working on solving this problem I realized that I could solve the counting backwards problem by counting forward. This resulted in the code below.
This solution seems almost to easy. Lets add some additional tests to verify.
All of the tests are passing! So we are done … yes? Maybe not. Our current solution requires almost two passes through the SLL. We could do it with only one pass if we track the nth position back from the current position. To keep the code simple I will allow myself to use an array in this solution.
I think we are done for the day. Tomorrow we will start looking into list flattening.
tags: Algorithm - Algorithmathon - RSpec - Ruby - Single Linked List