繁体   English   中英

如何遍历链表并打印与输入匹配的每条数据?

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

我正在研究这种方法,但遇到了问题。 当我输入一个与链表索引中的数据匹配的单词时,它只打印链表的第一个索引,其次数与我输入的单词在整个链表中出现的次数相同。

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;
    }
}

例如:链表包含这些字符串数据及其各自的索引(球弹得远,狗玩球,我最喜欢的玩具是球)。 如果我将输入输入为“球”,我希望它打印为

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

但是,它只打印出这个:

balls bounce far
balls bounce far
balls bounce far

Ball 出现 3 次,它只打印出链表的第一个索引输入出现的次数。

如果strTemp.contains(strInput)不满足temp = temp.next; 不会被执行,因此 while 循环会卡住。 temp = temp.next; 在 if 语句之外。

我已经解决了这个问题。 问题出在我的getCurrent()方法上。 当我需要返回temp.data时,它正在返回current.data 感谢所有帮助过的人! 我很感激。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM