链表java参考
我有一个链表java实现,但有一部分我不明白,我的类是链表java参考,java,linked-list,insert,implementation,Java,Linked List,Insert,Implementation,我有一个链表java实现,但有一部分我不明白,我的类是 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(curr
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);
}
}
我不明白的是,首先我们将头设置为当前变量。
将下一个节点传递给当前对象进行遍历
我的问题是它是如何工作的,因为current有ref of head,所以当你在技术上分配另一个值时,你就是在改变head。我可以用int数据看到这一点。如果我将current.data更新为0,则我看到头部受到影响
可能是一个低于标准的问题,但是请帮助我理解这里发生的事情…
基本上这个函数是添加新元素作为链表集合的头元素。每个元素都有一个对下一个元素的引用,所以只要下一个元素不存在,它就会遍历,然后将其设置为新元素(具有传递给函数的数据)。我不确定是否理解您的担忧,但通过更改“current”变量,您只是更改了对象的“引用”,而不是更改对象本身。因此,只要下一个项目不存在,您只需更改引用,然后创建一个新对象,并将其设置为前head引用的对象(此对象将成为新head)我重新排列了代码,以便于理解,并添加了注释:
/**
*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=[在此处输入另一个节点]
,将不同的节点分配给head节点。在Java中,=
表示赋值,=
表示相等。赋值和相等是两个不同的概念
单链表示例:1->2->3->NULL
(我们知道头=节点(1))
现在,假设用户调用insert(head,4)
执行步骤:
节点current=head
,因此current==节点(1)和head==节点(1)(current和head是两个不同的节点,但目前具有相同的值)head
为空,因此执行if语句中的语句current.next==节点(2)
所以它不是空的。在while循环中执行语句current=current。下一步
so current被分配到节点(2)current.next==节点(3)
所以它不是空的。在while循环中执行语句current=current。下一步
so current被分配到节点(3)current.next==NULL
,因此在循环时停止current.next=新节点(4)
,因此我们将节点(4)分配给current.next