how to iterate through linked list javascript

How to Iterate Through Linked List in JavaScript

If you are working with linked lists in JavaScript, you may need to iterate through the elements of the linked list. Here are a few ways to do it:

1. Using a While Loop

One common way to iterate through a linked list is to use a while loop. Here is an example:


    let currentNode = head;
    while(currentNode) {
      console.log(currentNode.value);
      currentNode = currentNode.next;
    }
  

In this example, we start at the head of the linked list and loop through each node until we reach the end of the linked list (when currentNode is null).

2. Using a For Loop

You can also use a for loop to iterate through a linked list. Here is an example:


    for(let currentNode = head; currentNode; currentNode = currentNode.next) {
      console.log(currentNode.value);
    }
  

In this example, we use a for loop to loop through each node in the linked list. The for loop is essentially the same as the while loop, but it is more concise.

3. Using Recursion

Another way to iterate through a linked list is to use recursion. Here is an example:


    function iterateLinkedList(node) {
      if(node) {
        console.log(node.value);
        iterateLinkedList(node.next);
      }
    }
    iterateLinkedList(head);
  

In this example, we define a recursive function called iterateLinkedList that takes a node as a parameter. The function checks if the node is null, and if not, it logs the value of the node and calls itself with the next node in the linked list.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe