【发布时间】:2019-10-26 17:28:09
【问题描述】:
我目前正在尝试理解和可视化 Java 中的链接列表。
我了解链表的基本概念以及如何在链表头部添加节点。但是,我不明白新节点是如何添加到链表末尾的。
例如,在以下代码中:
public class LinkedList
{
Node head; // head of list
/* Linked list Node*/
class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
public void append(int new_data)
{
/* 1. Allocate the Node &
2. Put in the data
3. Set next as null */
Node new_node = new Node(new_data);
/* 4. If the Linked List is empty, then make the
new node as head */
if (head == null)
{
head = new Node(new_data);
return;
}
/* 5. This new node is going to be the last node, so
make next of it as null */
new_node.next = null;
/* 6. Else traverse till the last node */
Node last = head;
while (last.next != null)
last = last.next;
/* 7. Change the next of last node */
last.next = new_node;
return;
}
public static void main(String[] args)
{
/* Start with the empty list */
LinkedList llist = new LinkedList();
// Insert 6. So linked list becomes 6->NUllist
llist.append(6);
// Insert 4 at the end. So linked list becomes
// 6->4->NUllist
llist.append(4);
llist.printList();
}
public void printList()
{
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.data+" ");
tnode = tnode.next;
}
}
}
虽然我可以可视化遍历(last 到达 llist 的末尾),但我不明白为什么 last = last.next;(在 public void append(int new_data) 中)将节点链接到前一个节点(为什么前一个 @987654327 @ 指向它)。
感谢您的支持!
【问题讨论】:
-
这是visualization for linked lists,希望对您有所帮助。
标签: java linked-list