[英]Appending unique values in a singly linked list in java
I want to append into a linked list without duplication of values. 我想附加到链表中而不重复值。 This is my function: But this does not filter out duplicates.
这是我的功能:但这不会过滤出重复项。 Any idea where I am going wrong?
知道我要去哪里错了吗? Node consists a string value and a next pointer.
Node由字符串值和下一个指针组成。
public static void append( Node head, Node newNode ) {
Node currentNode = head;
while( currentNode.next != null ) {
if(currentNode.value.trim().equals(newNode.value.trim())) {
return;
}
currentNode = currentNode.next;
}
currentNode.next = newNode;
}
You're not checking the final node for duplication (as jtahlborn said in his answer, which was deleted when I started writing this one...). 您没有检查重复的最后一个节点(正如jtahlborn在他的回答中说的那样,当我开始编写此节点时,它已被删除...)。 You need to keep going until
currentNode
is null, but you also need to remember the previous node so you can use it as the tail node. 您需要继续操作直到
currentNode
为null,但是还需要记住前一个节点,以便可以将其用作尾节点。
Here's a short but complete program showing it working. 这是一个简短但完整的程序,显示了它的工作原理。 It's got nasty package-access fields etc, but it works...
它有令人讨厌的包访问字段等,但是它可以工作...
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;
}
}
you never check the last node for duplication. 您永远不会检查最后一个节点是否重复。
best way to find problems like this in the future is to step through your code in a debugger, not ask questions on a forum. 将来发现此类问题的最佳方法是在调试器中逐步执行代码,而不是在论坛上提问。 otherwise, you will never learn to code on your own.
否则,您将永远不会学会自己编写代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.