Skip to content
DSA in JavaScript
Linked Lists, Stacks & Queues

Linked List Traversal

Algorithm · Starter

Level: StarterFast & Slow Pointers

Step through it: Fast & Slow Pointers pattern

1slow, fast
→
2
→
3
→
4
→
5
↩ tail points to node 3

both start at node 1

Step 1 of 6

Question: does this chain of nodes loop back on itself? Walking it one node at a time never answers that, because inside a loop you just keep going. Instead send two walkers from the start: a slow one moving 1 node per step and a fast one moving 2.

The task is to traverse the given linked list in straight order.

For example for the following linked list:

The order of traversal should be:

12 → 99 → 37

The time complexity is O(n) because we visit every node only once.

Reference

Code

traversal.js
/**
 * Traversal callback function.
 * @callback traversalCallback
 * @param {*} nodeValue
 */

/**
 * @param {LinkedList} linkedList
 * @param {traversalCallback} callback
 */
export default function traversal(linkedList, callback) {
  let currentNode = linkedList.head;

  while (currentNode) {
    callback(currentNode.value);
    currentNode = currentNode.next;
  }
}

Practice

Spotted a mistake or something unclear? Report it on GitHub.

On this page