count string in linked list javascript

Counting Strings in a Linked List Using JavaScript

If you're working with a linked list in JavaScript and need to count the number of strings within it, there are a few different approaches you can take.

Method 1: Using a Loop

One way to count the number of strings in a linked list is to loop through each node and check if its value is a string. Here's an example of how this could be done:


let count = 0;
let currentNode = head;

while (currentNode !== null) {
  if (typeof currentNode.value === 'string') {
    count++;
  }
  currentNode = currentNode.next;
}

console.log(count);

In this code, we start by initializing the count variable to 0 and setting the currentNode variable to the head of the linked list. We then loop through each node in the list, checking if its value property is a string. If it is, we increment the count variable. Finally, we move on to the next node in the list by setting currentNode to its next property.

Method 2: Using Recursion

Another way to count the number of strings in a linked list is to use recursion. Here's an example:


function countStrings(node) {
  if (node === null) {
    return 0;
  }
  if (typeof node.value === 'string') {
    return 1 + countStrings(node.next);
  } else {
    return countStrings(node.next);
  }
}

console.log(countStrings(head));

In this code, we define a function called countStrings that takes a node as its argument. If the node is null (i.e. we've reached the end of the linked list), we return 0. Otherwise, we check if the node's value property is a string. If it is, we return 1 plus the result of calling countStrings on the next node in the list. If it's not a string, we simply call countStrings on the next node.

Method 3: Using the Filter Method

Finally, if you're using JavaScript ES6 or later, you can use the filter method to count the number of strings in a linked list:


const count = list.filter(node => typeof node.value === 'string').length;

console.log(count);

In this code, we first call the filter method on the linked list, passing in a function that checks if each node's value property is a string. This returns a new array containing only the nodes where this condition is true. We then get the length of this array, which gives us the count of strings in the linked list.

Note: In all these methods, "head" represents the first node of 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