这与Hackerrank本身有关。我尝试了自己的解决方案,该解决方案前段时间通过了所有测试,但在存在循环的情况下也失败了。所以,我看了一下Hackerrank insertNode
用于在测试用例中创建列表的方法:
public void insertNode(int nodeData) {
// here a new node object is created each time a method is called
SinglyLinkedListNode node = new SinglyLinkedListNode(nodeData);
if (this.head == null) {
this.head = node;
} else {
this.tail.next = node;
}
this.tail = node;
}
然后它是如何在他们的main
:
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int tests = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int testsItr = 0; testsItr < tests; testsItr++) {
int index = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
SinglyLinkedList llist = new SinglyLinkedList();
int llistCount = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < llistCount; i++) {
int llistItem = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
// a new node is inserted each time so no cycle can be created whatsoever.
llist.insertNode(llistItem);
}
boolean result = hasCycle(llist.head);
bufferedWriter.write(String.valueOf(result ? 1 : 0));
bufferedWriter.newLine();
}
bufferedWriter.close();
scanner.close();
}
正如您所看到的,每个llistItem
值llist.insertNode(llistItem)
都被调用以将项目添加到列表中。但是,此方法无法创建循环,因为它每次都会创建一个新循环。 SinglyLinkedListNode
因此,即使某些llistItem
值相同,包含它们的节点也总是不同的。
更新
截至 2020 年 1 月 5 日,Hackerrank测试已修复,并且 OP 提供的解决方案通过了所有测试。