为什么头节点在 printLL() 函数中没有改变?

Why head node is not changing in printLL() function?

我正在尝试打印链表。 head 和 node 都是彼此的引用,但是在 printLL() 函数的 while 循环之后,head 并没有改变。 while 循环结束后节点为 null 但 head 仍指向 10。为什么会这样?

class Node { 
    int data;
    Node next;

    Node(int value) {
        this.data = value;
        this.next = null;
    }
}

class LL {
    Node head;

    void createLL() {
        head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
    }

    void printLL() {
        Node node = head;
        System.out.println("Printing full Linked List");

        while (node != null) {
            System.out.println(node.data);
            node = node.next;
        }
        System.out.println("Value of head is " + head.data);
        if (head.equals(node)) {
            System.out.println("head and node both are same");
        }

        else {
            System.out.println("head and node are not same");`
        }

    }
}



// Output - 

// Printing full Linked List
// 10
// 20
// 30
// 40
// Value of head is 10
// head and node are not same

什么是链表?

A linked list is formed by nodes that are linked together like a chain. Each node holds data, along with a pointer to the next node in the list.

下图显示了单链表的基本结构。

如您所见,单链表包含一个头节点:一个指向列表第一个元素的指针。每当我们想要遍历列表时,我们都可以使用这个头节点来完成。

现在使用下面的createLL()方法,你已经创建了一个链表,

    void createLL() {
            head = new Node(10);
            head.next = new Node(20);
            head.next.next = new Node(30);
            head.next.next.next = new Node(40);
        }

为了便于理解,可以用下图表示,

因此,在 createLL 方法中,您现在创建了一个链表,如


    10->20->30->40->null

这里第一个节点也被称为“头节点”包含数据10。

现在在方法printLL()中,第一行如下,

    Node node = head;

在这里您创建了一个名为“node”的临时节点并将其赋值给head。头部包含下一个节点的信息,下一个节点包含其下一个节点的信息,依此类推。所以现在使用您的临时节点“节点”并为其分配头节点的值,您可以遍历您通过方法 createLL() 创建的整个链表。

在下面的 while 循环中,

while (node != null) {
        System.out.println(node.data);
        node = node.next;
    }

你现在已经一个一个遍历了链表,直到到达null。请记住,链表的最后一个节点始终指向 null。这个 while 循环没有重新分配任何节点的 value/data。但它只是从第一个节点迭代到使用称为“节点”的临时节点到达最后一个节点。 while 循环最终将“node”变量赋值给 null。

所以在if循环比较中,

    if (head.equals(node))

你在比较,

if(10.equals(null)

这将 return 为假,因为头节点仍然指向 10 本身。只有临时节点“node”指向 null,它不会影响头节点或您创建的链表的任何节点。