2016-08-11 8 views
-1

能否请您描述它的使用下面的代码和它是如何工作。是否有必要使用静态嵌套类来创建一个节点链表

class LinkedList 
{ 
    Node head; // head of list 
    static class Node { 
     int data; 
     Node next; 
     Node(int d) { data = d; next=null; } // Constructor 
    } 

    public static void main(String[] args) 
    { 
     LinkedList llist = new LinkedList(); 

     llist.head = new Node(1); 
     Node second = new Node(2); 
     Node third = new Node(3); 

     llist.head.next = second; // Link first node with the second node 
     second.next = third; // Link second node with the third node 
    } 
} 
+1

不一定 – JavaHopper

回答

0

尽管这绝对是一个好主意,但并不是必需的。

您可以使用一个顶级类的链表的节点,而不是一个嵌套的一个。

您也可以使用非静态类,但您必须在您的LinkedList类上提供工厂方法以创建新节点。结果也会有点浪费,因为每个节点都会隐式引用列表。

请注意,您的代码编译的原因是您的main位于LinkedList类中。因此,它可以创建新的节点,而无需使用其外部类的名称来限定Node。如果你是移动main一些其他类,你将不得不使用此语法:

LinkedList.Node second = new LinkedList.Node(2); 
+0

但是你可以让我知道为什么节点头已经嵌套类的外侧。 –

+0

@PiyushMishra因为它是外部类的成员,而不是嵌套类的成员。 – dasblinkenlight

相关问题