我在eclipse中使用java创建了一个简单的单链表程序。我创建了一个主类和2个类文件node.java和linkedlist.java,但是我无法实例化类型节点,但是我的节点类不是静态的。我不能实例化类型节点吗?
app.java
package linkedlist.singlelinkedlist;
This is my main class
/**
* Hello world!
*
*/
public class app
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
LinkedList list=new LinkedList();
list.insert(10);
list.insert(15);
list.insert(20);
list.show();
}
}
node.java
This is my node class file
public class Node {
int data;
Node next;
}
linkedlist.java
这是我的LinkedList类文件
public class LinkedList {
Node head;
public void insert(int data)
{
Node node=new Node();#why cant i instantiate node?
node.data=data;
node.next=null;
if(head==null)
{
head=node;
}
else
{
Node n=head;
while(n.next!=null)
{
n=n.next;
}
n.next=node;
}
}
public void show()
{
Node x=head;``
while(x.next!=null)
{
System.out.println(x.data);
x=x.next;
}
System.out.println(x.data);
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Cannot instantiate the type Node
data cannot be resolved or is not a field
next cannot be resolved or is not a field
next cannot be resolved or is not a field
next cannot be resolved or is not a field
next cannot be resolved or is not a field
at linkedlist.singlelinkedlist.LinkedList.insert(LinkedList.java:9)
at linkedlist.singlelinkedlist.app.main(app.java:13)
Hello World!
如何实例化类型节点并纠正错误?
答案 0 :(得分:-1)
我刚刚编译了您的代码,它运行正常。
注意:LinkedList也是本机Java类。确保您的程序未指向本机类而不是类。
代码:
package me.PauMAVA.Tests;
public class Main
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
LinkedList list=new LinkedList();
list.insert(10);
list.insert(15);
list.insert(20);
list.show();
}
}
package me.PauMAVA.Tests;
public class LinkedList {
Node head;
public void insert(int data)
{
Node node=new Node();
node.data=data;
node.next=null;
if(head==null)
{
head=node;
}
else
{
Node n=head;
while(n.next!=null)
{
n=n.next;
}
n.next=node;
}
}
public void show()
{
Node x=head;
while(x.next!=null)
{
System.out.println(x.data);
x=x.next;
}
System.out.println(x.data);
}
}
package me.PauMAVA.Tests;
public class Node {
int data;
Node next;
}
输出:
Hello World!
10
15
20