链表 java 参考

linked list java refernce

我得到了一个链表 java implementation.But 我没有的部分 understand.my class 是

class Node {
    int data;
    Node next;
    Node(int d) {
        data = d;
        next = null;
    }
}

我要插入一个 fn

public static  Node insert(Node head,int data) {
  Node current = head;

  if(head!=null){
    while(current.next!=null){
      current = current.next;  
    }

    current.next = new Node(data);

    return head;
  } else {
    return head=new Node(data);
  }
}

我不明白的是,首先我们将 head 设置为当前变量。 并将下一个节点传递给当前对象进行遍历。

我的问题是它是如何工作的,因为 current 有 head 的引用,所以当你在技术上分配另一个值时,你正在改变 head。我可以看到使用 int data.if 我将 current.data 更新为 0 然后我看到头部受到影响..

可能是低于标准的问题,但请帮助我了解这里发生的事情...

基本上这个函数是添加新元素作为链表集合的 HEAD 元素。每个元素都有对 NEXT 元素的引用,因此只要下一个元素不存在,它就会遍历,然后将其设置为新元素(具有您传递给函数的数据)。 我不确定我是否理解您的顾虑,但是通过更改 "current" 变量,您只是将 "reference" 更改为一个对象,而不是更改对象本身。因此,只要下一个项目不存在,您就可以更改引用,然后创建一个新对象并设置为前一个头引用的对象(并且该对象成为一个新头)

我重新整理了代码,使其更易于理解,并添加了注释:

/**
 *Insert a leaf node in a linked list
 *@param head represents the head node of the list.
 *@return the head node 
 */
public static  Node insert(Node head,int data) {

     //if head does not exist, create it and return it 
    if (head==null) {
        return head=new Node(data);
    }

    else{//head exist

        //search for the end of the linked list (leaf, has no next node)
        Node current = head;
        while(current.next!=null){
            current = current.next;  
        }
        //at the end of loop the current.next == null (leaf)
        //add new node as leaf
        current.next = new Node(data);
        return head; //return head unchanged 
    } 

}

我希望它有助于澄清。

当您将某个节点(不仅仅是值)分配给当前节点时,您并不是在更改该特定节点。在这里,您已将 head 指定为当前节点。但这并不意味着两个节点现在相同。他们还是不一样的。 head 节点将始终具有相同的值,直到有人专门键入 head = [enter another node here],将不同的节点 分配给 头节点。在Java中,=表示赋值,==表示等于。所以赋值和equals是两个不同的概念。

示例单链表: 1 -> 2 -> 3 -> NULL (我们知道 head = Node(1)) 现在,假设用户调用 insert(head, 4)

执行步骤:

  1. Node current = head,所以 current == Node(1) 和 head == Node(1)(current 和 head 是两个不同的节点,但现在具有相同的值)
  2. head为空,所以执行if语句
  3. 中的语句
  4. current.next == Node(2) 所以它不为空。在while循环中执行语句
  5. current = current.next 所以 current 被分配到 Node(2)
  6. current.next == Node(3) 所以它不为空。在while循环中执行语句
  7. current = current.next 所以当前分配给 Node(3)
  8. current.next == NULL,所以停止 while 循环
  9. current.next = new Node(4),所以我们将Node(4)分配给了current.next
  10. 现在我们 return 从头开始​​列出。 head = Node(1) 仍然。

结果:1 -> 2 -> 3 -> 4 -> NULL