You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LinkedList遍历输出重复最后元素:如何获取节点多字段值?

LinkedList遍历toString()重复输出最后一个节点信息的修复方法

问题描述

我实现的LinkedList中每个节点包含StudentID、Group、Priority三个字段,重写toString()方法遍历链表时,始终输出最后一个学生的信息,而非对应节点的内容,求修改方案。

原代码

public String toString() {
    System.out.println("--------------------------------------");
    String str = " ";

    ListNode current = head;
    while (current != null) {
        str += "StudentID: " + StudentAdd.getStudentID() + " is in Group " +
            StudentAdd.getGroup().toUpperCase() + " with priority " + 
            StudentAdd.getPriority();
            str += "]\n";
            current = current.getNext();

        }
        
        return str;
    }

期望输出

[StudentID:0001 is in Group A with Priority 1]
[StudentID:0005 is in Group C with Priority 1]
[StudentID:0220 is in Group B with Priority 2]
[StudentID:0200 is in Group B with Priority 2]
[StudentID:0215 is in Group B with Priority 2]
[StudentID:0315 is in Group B with Priority 3]
[StudentID:0301 is in Group B with Priority 3]
[StudentID:0350 is in Group B with Priority 3]

实际输出

[StudentID:0350 is in Group B with Priority 3]
[StudentID:0350 is in Group B with Priority 3]
[StudentID:0350 is in Group B with Priority 3]
[StudentID:0350 is in Group B with Priority 3]
[StudentID:0350 is in Group B with Priority 3]
[StudentID:0350 is in Group B with Priority 3]
[StudentID:0350 is in Group B with Priority 3]
[StudentID:0350 is in Group B with Priority 3]

问题原因及修复方案

问题核心:你当前代码调用的StudentAdd.getStudentID()这类方法,是获取全局/静态的最后一次添加的学生数据,而非当前遍历节点的学生信息。必须从当前遍历的current节点中取出对应Student实例,再调用其get方法。

另外补充两个优化点:

  • 字符串拼接用StringBuilder替代直接+=,避免频繁创建字符串对象,提升效率
  • 修复输出格式,补上缺失的[符号,和期望输出对齐

修改后的代码

public String toString() {
    System.out.println("--------------------------------------");
    StringBuilder str = new StringBuilder();

    ListNode current = head;
    while (current != null) {
        // 从当前节点获取对应的Student对象
        Student student = current.getStudent();
        str.append("[StudentID: ")
           .append(student.getStudentID())
           .append(" is in Group ")
           .append(student.getGroup().toUpperCase())
           .append(" with priority ")
           .append(student.getPriority())
           .append("]\n");
        current = current.getNext();
    }
    
    return str.toString();
}

注:假设你的ListNode类中存在getStudent()方法,用于返回该节点存储的Student实例;如果节点直接存储三个字段(而非Student对象),则直接调用current.getStudentID()、current.getGroup()、current.getPriority()即可。

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 18:42:34