Reversing a Linked List

As with many coding interview questions, the “usefulness” of a specific puzzle seems “useful” mostly in the context of getting a job. That said, if you need to use some data model to simulate some process in manufacturing, perhaps something where a “setup” requires a bunch of complicated bits and pieces to be entered “left to right” into some tube… but in order for the assembly to take place, perhaps you need to start at the right and then iterate leftward.

Another possible real world simulation is you’re an investigator doing data forensics, and you’ve been piling up clues in a certain direction… suppose though you have have several thousand bits of data. And yet… in order to appreciate/understand what you’re looking at/working with, you may need to reverse the order of the clues.

class Node {
  constructor(value, next = null) {
    this.value = value;
    this.next = next;
  }
}

function reverse(head) {
  let current = head;
  let thePreviousNodeValueIfGoingForward = null;
  while (current !== null) {
    tempGoingForward = current.next;
    current.next = thePreviousNodeValueIfGoingForward;
    thePreviousNodeValueIfGoingForward = current;
    current = tempGoingForward;
  }
  return thePreviousNodeValueIfGoingForward;
}

const head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);

console.log(head)
console.log(reverse(head))

Cast of Characters:
-Classroom
-Wart Nose
-Construction Workers
-Two Face
-Wile E Coyote
-Street Magician

Glossary of Code Personified

Return to the Pattern Directory

Discover more from Comedy Tragedy Epic

Subscribe now to keep reading and get access to the full archive.

Continue reading