无法显示在链表末尾的节点插入

问题描述 投票:0回答:2

我目前正在尝试理解和可视化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)中)将节点链接到前一个节点(为什么上一个.next指向它)。

感谢您的支持!

java linked-list
2个回答
0
投票

基本链接列表只是从Head节点开始,列表中的每个节点都指向列表中的下一个节点。最后一个节点的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;

它从头开始,然后看着它的next。如果不是null,则表示它仍然不是列表的实际最后一个节点,因此它将last变量设置为下一个。直到最后,它找到将其next设置为null的那个。当while循环结束时,last变量才是真正的最后一个。

然后将next节点的last设置为新节点。新节点的next已经设置为null,因此下一次遍历将是last节点。


0
投票

[如果您只是将代码更改为类似的代码但仍然可以实现相同但又给您带来另一种观点,可能会有所帮助。有时,变量的名称会让您感到困惑。

为了更好地理解,将last重命名为current,因为您从头开始,然后依次查看每个节点,直到找到一个节点,其中next指向null表示列表的末尾。

请记住,.next本身是一个节点,current被用作迭代器。您也可以将其写为for循环:

Node current = head;
for(current; current.next != null; current.next)
//now current refers to the last node since current.next now points to null
current.next = new_node;
//The new end is now new_node - new_node.next points to null
© www.soinside.com 2019 - 2024. All rights reserved.