我正在尝试编写一个程序来反转给定的链表。首先,我将从用户那里读取数字并将其传递给将数字转换为LinkedList的函数,然后将链表传递给帮助函数,该函数将反转给定的LinkedList。
这是我的程序:
import java.io.*;
import java.util.*;
public class Solution {
public class Link {
Node head;
public class Node {
int data;
Node next;
Node(int x) {
data = x;
next = null;
}
} // End of class Node
public void printList() {
Node n = head;
while (n != null) {
System.out.print(n.data+" ");
n = n.next;
}
}
public void createList(String num) {
this.head = new Node(num.charAt(0));
Node prev = head ;
for(int i = 1; i < num.length(); i++) {
Node newNode = new Node(num.charAt(i));
prev.next = newNode;
prev = newNode;
}
}
} // end of class Link
public Node reverse(Node curr) {
if (curr == null) return null;
if(curr.next != null) {
Node forward = reverse(curr->next);
curr.next.next = curr ;
curr.next = null;
} else {
return res;
}
return forward;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String number1 = sc.next();
// System.out.println(number1);
String number2 = sc.next();
//System.out.println(number2);
Link first = new Link();
first.createList(number1);
first.printList();
System.out.println("''''''''''");
Link second = new Link();
second.createList(number1);
second.printList();
System.out.println("''''''''''");
first.head = reverse(head);
first.printList();
System.out.println("''''''''''");
second.head = reverse(head);
second.printList();
System.out.println("''''''''''");
}
}
这是我得到的错误:
Solution.java:47: error: cannot find symbol
public Node reverse(Node curr)
^
symbol: class Node
location: class Solution
Solution.java:47: error: cannot find symbol
public Node reverse(Node curr)
^
symbol: class Node
location: class Solution
2 errors
我的问题是,即使Link类和Node类都是公共的,为什么反向方法不能访问符号Node?以及应该如何编写Java中的辅助方法,以便它们访问任何类的对象。
答案 0 :(得分:0)
问题是您的类是内部类,而内部类的实例只能与外部类的实例一起使用。如果您将类设置为顶级,这是一个可能的解决方案,事情应该没事(您还必须修复反向方法)
class Node {
int data;
Node next;
Node(int x) {
data = x;
next = null;
}
}
class Link {
Node head;
public void printList() {
Node n = head;
while (n != null) {
System.out.print(n.data + " ");
n = n.next;
}
}
public void createList(String num) {
this.head = new Node(num.charAt(0));
Node prev = head;
for (int i = 1; i < num.length(); i++) {
Node newNode = new Node(num.charAt(i));
prev.next = newNode;
prev = newNode;
}
}
}
public class Solution {
public Node reverse(Node curr) {
// to be implemented
return null;
}
}