如何打印ListNode数组中的所有节点值?
解决ListNode数组所有节点值的打印问题
你的问题出在仅遍历了数组中的每个ListNode头节点,没有深入遍历每个链表的后续节点。要输出所有节点值,需要在遍历数组的同时,对每个链表做链式遍历,直到节点为null。
修改后的核心代码
public static void main(String[] args) { ListNode lists[] = { new ListNode(1, new ListNode(4, new ListNode(5))), new ListNode(1, new ListNode(3, new ListNode(4))), new ListNode(2, new ListNode(6)) }; // 遍历数组中的每个链表 for(ListNode ln : lists){ // 嵌套循环遍历当前链表的所有节点 ListNode current = ln; while(current != null){ System.out.print(current.val + ", "); current = current.next; // 移动到下一个节点 } } }
输出格式优化(可选)
如果需要和期望输出格式完全一致(包裹方括号、无末尾冗余逗号),可以用StringBuilder拼接结果:
public static void main(String[] args) { ListNode lists[] = { new ListNode(1, new ListNode(4, new ListNode(5))), new ListNode(1, new ListNode(3, new ListNode(4))), new ListNode(2, new ListNode(6)) }; StringBuilder result = new StringBuilder("["); for(ListNode ln : lists){ ListNode current = ln; while(current != null){ result.append(current.val); // 判断是否需要添加逗号:当前节点不是链表最后一个,或不是整个数组最后一个节点的最后元素 if(current.next != null || (current.next == null && ln != lists[lists.length-1])){ result.append(", "); } current = current.next; } } result.append("]"); System.out.println(result.toString()); }
运行后输出:[1, 4, 5, 1, 3, 4, 2, 6],完全符合期望。
内容的提问来源于stack exchange,提问作者Joe Kennedy
相关产品推荐
相关产品推荐

