简体   繁体   English

链表Java实现的主要内容

[英]What is head in Linked List Java Implementation

I am reading "Cracking the Coding interview" and I noticed the code below for a Linked List implementation in Java. 我正在阅读“破解编码面试”,并且注意到下面的Java链表实现代码。

class Node {
    Node next = null;
    int data;

    public Node (int d){
        data = d;
    }

    void appendToTail(int d){
        Node end = new Node(d);
        Node n = this;
        while(n.next != null){
            n = n.next;
        }
        n.next = end;
    }
}

The line Node n = this; Node n = this; confuses me very much. 非常让我感到困惑。 We are supposed to start at the head of the list and go till the end of the list. 我们应该从列表的开头开始,一直到列表的末尾。 "This" in java usually refers to the current instance. Java中的“ this”通常是指当前实例。 So, how are these two related? 那么,这两个有什么关系? I'm sure I am missing something here. 我确定我在这里缺少什么。 Please help! 请帮忙!

Whenever, for Node reference someNode , someNode.appendToTail(x) is called, it will create a new Node with data value x , and append it to the tail of whatever list contains someNode . 每当为Node引用someNode someNode.appendToTail(x) ,它将创建一个数据值为x的新Node ,并将其附加到包含someNode的任何列表的someNode If someNode is not already part of a list, it will, afterwards, be the head of a two node list with the new node as tail. 如果someNode是列表的一部分,则它将成为两个节点列表的开头,而新节点为结尾。 If someNode is part of a longer list, the new node will be the tail of that list. 如果someNode是较长列表的一部分,则新节点将是该列表的someNode

To do that, appendToTail has to find the tail note, the one with a null next pointer. 为此, appendToTail必须找到尾注,即next指针为null的尾注。 It starts the search with itself, using this . 它使用this本身开始搜索。 If it is the tail of its list, the loop will be skipped because next is null , and the n.next = end; 如果它是列表的n.next = end; ,则将跳过该循环,因为nextnull ,并且n.next = end; assignment will have the effect of next = end; 分配将具有next = end;的效果next = end; . If there are more nodes in the list, the while loop will skip over them until it finds the current tail. 如果列表中还有更多节点,则while循环将跳过它们,直到找到当前尾部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM