我需要帮助使这个toString方法传递到底部的测试。我目前正在收到错误(预期:< 0:20,1:[1] 0>但是< 0:20,1:[2] 0>)。 addFirst 100%工作,但我不确定这里有什么问题。
public class LList
{
public Node head;
private int i;
private int size;
public void addFirst(int value)
{
Node n = new Node();
n.value = value;
n.next = head;
head = n;
}
public void removeFirst()
{
if (head != null)
{
// commone case: there is at least one node
head = head.next;
}
else
{
// no nodes
throw new Banana();
}
}
public int size()
{
Node current = head;
int count = 0;
while(current != null)
{
count++; // keep count of nodes
current = current.next; // move to next node
}
return count;
}
public int get(int index)
{
int count = 0;
Node current = head;
if (index < 0 || index >= size())
{
throw new Banana();
}
while(count != index)
{
count++;
current = current.next;
}
return current.value;
}
public String toString()
{
String s = "";
Node current = head;
//current = head;
if (size() == 0)
{
return s;
}
else
{
s = s + "" + i + ":" + current.value;
for (int i = 1; i < size(); i++)
{
s = s + ", " + i + ":" + current.value;
}
return s;
}
}
public class Node
{
public int value;
public Node next;
}
@Test
public void testToString()
{
LList a = new LList();
assertEquals("", a.toString());
a.addFirst(10);
assertEquals("0:10", a.toString());
a.addFirst(20);
assertEquals("0:20, 1:10", a.toString());
a.addFirst(30);
assertEquals("0:30, 1:20, 2:10", a.toString());
}
答案 0 :(得分:0)
你应该迭代(遍历)所有节点。
使用while
循环,例如:
public String toString() {
String s = "";
Node current = head;
// current = head;
if (size() != 0) {
int i = 0;
s = s + "" + i + ":" + current.value;
while(current.next != null) {
i++;
current = current.next;
s = s + ", " + i + ":" + current.value;
}
}
return s;
}