Java遍历链表打印匹配数据时重复输出首节点问题求解
问题描述
实现链表的iteratePrint(T aData)方法时出现逻辑异常:当输入查询词匹配链表中多个节点的存储数据时,程序会按照整个链表中匹配项的总次数,重复打印链表首节点的内容,不会输出对应匹配的各节点内容。
复现场景:
- 链表按顺序存储3个字符串节点:
"balls bounce far"、"dogs play fetch with balls"、"my favorite toy is a ball" - 输入查询词
"ball"时,预期逐行打印三个匹配节点的对应内容,实际连续打印3次首节点内容"balls bounce far"——查询词在全表共匹配3次,首节点就被重复打印3次。
问题原代码:
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; } }
问题根因
遍历逻辑本身没有问题,temp指针确实在逐节点向后移动,bug出在打印语句调用的temp.getCurrent()方法上:该方法的实现存在错误,没有返回当前调用节点自身存储的data值,而是固定返回链表全局头节点head的存储内容。因此不管当前匹配到的是第几个节点,打印出来的永远是头节点的数据,全表匹配到多少次,就会重复打印多少次头节点内容。
修复方式
直接在匹配成功后读取当前temp节点的data属性打印即可,不需要调用存在逻辑错误的getCurrent()方法,修复后代码如下:
public void iteratePrint(T aData) { if (head == null) { return; } // 转换输入查询词为小写,统一匹配规则 String strInput = ((String)aData).toLowerCase(); // 初始化遍历指针指向头节点 ListNode temp = head; while(temp != null) { // 转换当前节点存储内容为小写,统一匹配规则 String strTemp = ((String)temp.data).toLowerCase(); if(strTemp.contains(strInput)){ // 直接打印当前节点存储的数据 System.out.println(temp.data); } // 指针移动到下一个节点 temp = temp.next; } }
如果需要保留getCurrent()方法的调用,就去修正ListNode类中该方法的实现,让它返回当前节点实例自身的data属性,不要关联全局头节点。
内容的提问来源于stack exchange,提问作者OMeihls
相关产品推荐
相关产品推荐

