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.

public void iteratePrint(T aData) {
    if (head == null) {
        return;
    }
    //Typecast aData to string, and make it lowercase.
    String a = (String)aData;
    String strInput = a.toLowerCase();

    //Create temp listnode to loop through.
    ListNode temp =  head;
    
    //While temp is not null, check for match and if so, print.
    while(temp != null) {

        //Typecast temp.data into string (all of the data is a string anyway) and
        //Make sure it is lowercase.
        String b = (String)temp.data;
        String strTemp = b.toLowerCase();
        
        //This checks for the match and prints the current line.
        //Not currently working
        if(strTemp.contains(strInput)){
            System.out.println(temp.getCurrent());
        }
        temp = temp.next;
    }
}

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

balls bounce far
dogs play fetch with balls
my favorite toy is a ball

However, it only prints out this:

balls bounce far
balls bounce far
balls bounce far

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.

8 People found this is helpful
Advertisement