我目前正在研究链表,我在 stackoverflow、geeksforgeeks 中查看了一些问题,我只是想弄清楚我的理解是否正确。在展示我的可视化之后,我还有一些问题。
下面是一个简单的java程序,介绍一个链表
public class LinkedList {
Node head;
public static void main (String [] args){
LinkedList list = new LinkedList();
list.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
list.head.next = second;
second.next = third;
}
}
class Node{
int data;
Node next;
Node(int d){
data = d;
next = null;
}
}
这将创建一个 LinkedList
(1,2,3)
据我了解这里是创建LinkedList的步骤,如果我错了,请纠正我
class LinkedList
和 class Node
class LinkedList
我声明了一个以后可以使用的对象是 Node head;
class Node
是另一个对象声明,它是 Node next;
和一个接受数据的构造函数(我创建了一组节点)class LinkedList
我实例化一个 object list
这将是节点的容器,所以它就像 class Node
的对象class LinkedList
的内部对象这是我的可视化:
我的问题是:
Node head = new Node(1);
而不是 Node head;
list
创建为 class Node
对象的容器那正确吗? Node next;
在 Node 构造函数内部,为什么我必须设置为 next = null;
? 最佳答案
Node head = new Node(1);
创建一个新节点只是他们在介绍单向链表的样子。 next = null;
因为稍后你会将每个节点链接到:llist.head.next = second; second.next = third
这是一个完整的表示:
/* Start with the empty list. */
LinkedList2 llist = new LinkedList2();
llist.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
/* Three nodes have been allocated dynamically.
We have references to these three blocks as head,
second and third
llist.head second third
| | |
| | |
+----+------+ +----+------+ +----+------+
| 1 | null | | 2 | null | | 3 | null |
+----+------+ +----+------+ +----+------+ */
llist.head.next = second; // Link first node with the second node
/* Now next of the first Node refers to the second. So they
both are linked.
llist.head second third
| | |
| | |
+----+------+ +----+------+ +----+------+
| 1 | o-------->| 2 | null | | 3 | null |
+----+------+ +----+------+ +----+------+ */
second.next = third; // Link second node with the third node
/* Now next of the second Node refers to third. So all three
nodes are linked.
llist.head second third
| | |
| | |
+----+------+ +----+------+ +----+------+
| 1 | o-------->| 2 | o-------->| 3 | null |
+----+------+ +----+------+ +----+------+ */
关于java - 这是 LinkedList 的正确可视化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61523131/