代码之家  ›  专栏  ›  技术社区  ›  Mayank Kumar Thakur

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

  •  0
  • Mayank Kumar Thakur  · 技术社区  · 4 年前

    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
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   Sreedhar S    4 年前

    什么是链表?

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

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

    现在使用下面的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);
            }
    

    为了便于理解,可以使用下面的图像来表示,

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

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

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

        Node node = head;
    

    在下面的while循环中,

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

    您现在已经逐个遍历了链表,直到它到达空值。记住链表的最后一个节点总是指向null。此while循环没有重新分配任何节点的值/数据。但它只是从第一个节点迭代到最后一个节点,使用一个名为“node”的临时节点。while循环最后将“node”变量赋值为null。

        if (head.equals(node))
    

    你在比较,

    if(10.equals(null)
    

    它将返回为假, 因为头节点仍然指向10本身