DEV Community

Discussion on: Acing Your Interview: Traversing a Linked List in JavaScript

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

An alternate solution using recursion:

const linkedList = {
  val: 5,
  next: {
    val: 3,
    next: {
      val: 10,
      next: null,
    },
  },
};

const getValuesFromLinkedList = (currentList = {}, currentValues = []) => {
  if (currentList.hasOwnProperty('val'))
    currentValues.push(currentList.val);
  if (currentList.hasOwnProperty('next') && typeof currentList.next === 'object' && currentList.next !== null && !Array.isArray(currentList.next))
    currentValues = getValuesFromLinkedList(currentList.next, currentValues);
  return currentValues;  
}

console.log(getValuesFromLinkedList(linkedList));

As silly as this sounds, if you can demonstrate (working) recursion during a whiteboard/screenshare interview, it often carries more weight with the interviewers than it warrants. Like you've certified yourself as a master of the dark arts.

I humbly submit that this solution is a bit more robust, because it doesn't depend upon the idea that there are given properties in the source object, or that they are set to a specific value of null. That while loop above is problematic if values other than Object/null are set on next.

Finally, by encapsulating the answer in a function, the function can truly operate as a standalone algorithm. But the while loop is dependent upon the setting of the head variable before you enter the loop.

Are all of these points incredibly nitpicky?? Yes. They absolutely are. I'm waiting for my next meeting to begin, and I'm bored. So I went through this in much more detail than you should expect in most interviews.

Cheers.