你没有检查最后一个节点是否有重复(正如 jtahlborn 在他的回答中所说,当我开始写这个时它被删除了......)。您需要继续直到currentNode
为空,但您还需要记住前一个节点,以便将其用作尾节点。
这是一个简短但完整的程序,展示了它的工作原理。它有讨厌的包访问字段等,但它有效......
class Test {
public static void main(String[] args) {
Node head = new Node("head");
append(head, new Node("foo"));
append(head, new Node("bar"));
append(head, new Node("bar"));
append(head, new Node("bar"));
append(head, new Node("baz"));
dump(head);
}
public static void append(Node head, Node newNode) {
Node currentNode = head;
Node previousNode = null;
while (currentNode != null) {
previousNode = currentNode;
if (currentNode.value.trim().equals(newNode.value.trim())) {
return;
}
currentNode = currentNode.next;
}
previousNode.next = newNode;
}
public static void dump(Node head) {
Node currentNode = head;
while (currentNode != null) {
System.out.println(currentNode.value);
currentNode = currentNode.next;
}
}
}
class Node {
String value;
Node next;
Node(String value) {
this.value = value;
}
}