有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中的链表“object=this”

我熟悉java中使用的“this”关键字,它用于引用当前对象。以下代码显示了如何创建LinkedList的节点:

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;
    }
}

但在这里,我不确定上面代码中的以下行说明了什么:

Node n = this;

我很确定这里的“this”指的是当前对象,但这个对象是头、尾还是LinkedList中的任何其他节点?我不确定我的问题是否合理,但非常感谢您的帮助


共 (1) 个答案

  1. # 1 楼答案

    I'm pretty sure that 'this' here is referenced to the current object

    是的

    but is this object head, tail or any other node in the LinkedList?

    这取决于调用方法的位置,或者列表是否包含this节点

    该方法所做的只是为当前节点分配一个临时引用,以便对其进行迭代。如果没有更多信息,就无法确定它是哪个节点


    从comments-如果你在头部调用appendToTail(),这将是头部。如果你叫它尾巴,这就是尾巴。如果你在中间节点上调用它,这就是那个中间节点