HackerRank中Compare Two LinkedList代码编译错误求助
解决HackerRank链表比较代码的编译错误
问题描述
我编写了用于比较两个链表的Java代码,逻辑无误,但在HackerRank平台运行时持续出现编译错误,错误提示为“类、接口或枚举期望”相关报错。
错误代码
import java.io.*; import java.math.*; import java.text.*; import java.util.*; import java.util.regex.*; public class Solution { static class SinglyLinkedListNode { public int data; public SinglyLinkedListNode next; public SinglyLinkedListNode(int nodeData) { this.data = nodeData; this.next = null; } } static class SinglyLinkedList { public SinglyLinkedListNode head; public SinglyLinkedListNode tail; public SinglyLinkedList() { this.head = null; this.tail = null; } public void insertNode(int nodeData) { SinglyLinkedListNode node = new SinglyLinkedListNode(nodeData); if (this.head == null) { this.head = node; } else { this.tail.next = node; } this.tail = node; } } public static void printSinglyLinkedList(SinglyLinkedListNode node, String sep, BufferedWriter bufferedWriter) throws IOException { while (node != null) { bufferedWriter.write(String.valueOf(node.data)); node = node.next; if (node != null) { bufferedWriter.write(sep); } } } // Complete the compareLists function below. /* * For your reference: * * SinglyLinkedListNode { * int data; * SinglyLinkedListNode next; * } * */ static boolean compareLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) { // while((head1 != null && head2 != null) && (head1.data == head2.data)){ // head1 = head1.next; // head2 = head2.next; // } // return (head1 == null && head2 == null); // } while((head1!=null && head2!=null) && head1.data == head2.data){ head1 = head1.next; head2 = head2.next; } return (head1 == null && head2 == null); } // 此处多余的}导致Solution类被提前闭合 }
错误信息
Solution.java:85: error: class, interface, or enum expected private static final Scanner scanner = new Scanner(System.in); ^ Solution.java:87: error: class, interface, or enum expected public static void main(String[] args) throws IOException { ^ Solution.java:90: error: class, interface, or enum expected int tests = scanner.nextInt(); ^ Solution.java:91: error: class, interface, or enum expected scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); ^ Solution.java:93: error: class, interface, or enum expected for (int testsItr = 0; testsItr < tests; testsItr++) { ^
解决方案
问题根源是代码末尾添加了多余的},导致Solution类被提前闭合。HackerRank平台会自动在用户提交的代码后追加scanner声明和main方法,这些代码必须位于Solution类内部才能通过编译。
修正方法:删除那个多余的},让Solution类正确包含所有方法,平台自动生成的代码就能正常嵌入类中。
修正后的核心代码片段(完整代码仅需移除多余的闭合括号):
// ... 前面的类和方法保持不变 static boolean compareLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) { while((head1!=null && head2!=null) && head1.data == head2.data){ head1 = head1.next; head2 = head2.next; } return (head1 == null && head2 == null); } // 此处不再保留多余的},平台自动添加的代码将位于类内部
内容的提问来源于stack exchange,提问作者Satendra Patel
相关产品推荐
相关产品推荐

