[英]Inner Class vs Static Inner Class
我正在嘗試使用內部類創建鏈接列表實現
package linkedlist;
public class linkedList {
public class Node
{
int data;
public Node next;
public Node(int k)
{
this.data = k;
this.next=null;
}
public Node addToHead(int data)
{
Node node = new Node(data);
Node current = this;
node.next=current;
return node;
}
}
public static void findn(Node head)
{
Node previous=head;
Node current = head;
int i =1;
while(current!=null)
{
if (i==6)
{
//System.out.println(current.data);
previous.next = current.next;
break;
}
previous=current;
current = current.next;
i++;
}
}
public static void main(String args[])
{
linkedList list = new linkedList();
linkedList.Node tail = linkedList.new Node(0);
// list.Node tail = list.Node(0);
Node head = tail;
for (int i=1;i<=20;i++)
{
head = head.addToHead(i);
}
findn(head);
while(head!=null)
{
System.out.println(head.data);
head = head.next;
}
}
}
我在主要功能中的問題是,我嘗試使用外部類創建一個節點。 但是,即使我遵循正確的語法,語法也會使我出錯。 我想知道此語句“ linkedList.Node tail = linkedList.new Node(0);”有什么問題。
作為非靜態內部類的Node需要其封閉類的實例 。 linkedList
是類名。 它沒有引用該類的實例。 所以應該
list.new Node()
如果您遵守Java命名約定,那就更加清楚了:變量以小寫字母開頭,而類以大寫字母開頭。
您可能應該在類linkedList,addToTail()中創建一個方法:
public void addToTail(int k) {
Node tail = new Node(k);
//loop through all the nodes in the list and add "tail" to the end
}
然后,您可以在main()中調用lst.addToTail(k),其中lst將是linkedList類的對象。
順便說一句,當您使用小寫字母開頭類名稱時,它會使代碼難以讀取。 它們通常以Java中的大寫字母開頭。 調用類LinkedList(以大寫字母開頭)也令人困惑,因為它可能會誤認為標准的java.util.LinkedList,因此也許可以將其命名為LinkedList0或其他名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.