Skip to content
Advertisement

How can I loop through a linked list and print each piece of data that matches the input?

I’m working on this method but am running into an issue. When I enter a word that matches the data in an index of the linked list, it only prints the first index of the Linked List the same number of times that the word I entered appears in the entire linked list.

JavaScript

For example: The linked list contains these as String data with their respective indices (balls bounce far, dogs play fetch with balls, my favorite toy is a ball). If I enter my input as “ball”, I would like it to print out as

JavaScript

However, it only prints out this:

JavaScript

Ball appears 3 times, and it is only printing out the first index of the linked list the amount of times that the input appears.

Advertisement

Answer

If strTemp.contains(strInput) is not satisfied temp = temp.next; will not get executed hence while loop will get stuck. Take temp = temp.next; outside of the if statement.

Advertisement