链表的 toString 方法

toString method for a linkedList

我的 linkedList 中的 toString 得到了奇怪的输出 class。

我不能使用任何方法,只能使用字符串连接。如何处理这个问题非常有限。

代码如下:

@Override
public String toString() {
if (head == null) {
return "";
}
String result = "";
Node curr = head;

while (curr.next != null) {
curr = curr.next;
result += curr.data + ", ";
}
return result;
}

我写了一个 JUnit 测试:

assetsEquals(
"8,6,7,5,3,0,9, " + "9,0,3,5,7,6,8", dataTest.noOrderList().toString());

并且 noOrderList().toString() 来自:

public static noOrderList<Integer> noOrderList() {
return makeListInNoOrder(new Integer[]{ 8, 6, 7, 5, 3, 0, 9, 9, 0, 3, 5, 7, 6, 8});

当我 运行 我得到的测试:

expected:<... 3, 0, 9, 9, 0, 3[]> but was: <... 3, 0, 9, 9, 0, 3[, ]>

这是造成这个的原因,在 [ ] 中我该如何消除那个逗号?

谢谢

你的覆盖行为有这个循环

while (curr.next != null) {
  curr = curr.next;
  result += curr.data + ", ";
}

当你到达它的末尾时,无论是否还有另一个逗号,你总是添加一个逗号 curr.next

如果你可以在循环之后删除它,如果不是你必须在添加逗号之前再检查一次 curr.next != null 或者开始将第一个字符串附加到循环之外并在内部开始连接用逗号

在您的 While 循环中,我们到达 curr.next != null 的最后一次迭代,我们仍然向其附加一个“,”。

您可以在添加逗号之前检查是否 curr.next.next ==。

您始终将 ", " 字符串附加到结果。

  • 因此,对于第一个元素,您附加 "9, ".
  • 第二个是"0, "
  • 等等...
  • 最后,你在最后添加"3, "

相反,只有当下一个元素不是 null.

时,您才应该附加 ", "

例如:

while (curr.next != null) {
curr = curr.next;
    result += curr.data;
    if (curr.next != null)
        result += ", ";
}

为了保存一些比较,您应该在元素之前发出 ", ",并在循环之前发出第一个元素:

//don't print head, since that seems to be empty in your implementation.
//also make sure head does not reference `null` by accident...
if (curr.next == null)
    return result;
curr = curr.next;

//1st element after `head`
result += curr.data;

while (curr.next != null) {
    curr = curr.next;
    result += ", " + curr.data;
}

我还注意到您从未将 head 元素放入结果中。是空的还是写错了?