在链表中,对象引用是如何工作的?(Java)

huangapple 未分类评论45阅读模式
英文:

How object reference works in Linkedlist (Java)?

问题

我正在构建一个链表。

public ListNode addNode(ListNode head, ListNode temp){
    if(head == null){
        head = temp;
    } else{
        ListNode curr = head;
        while(curr.next != null){
            curr = curr.next;
        }
        curr.next = temp;
    }
    return head;
}

我需要合并两个链表。例如,假设head为1->2->3->null,temp为4->5->null,我需要的输出是1->2->3->4->5->null。

在head链表中,我们需要移动到最后一个节点,以便可以合并temp链表。为了将指针移动到head链表的最后一个节点,我会迭代,直到获取到下一个元素为null,这意味着当while循环结束时,curr链表将只有3->null。然后,我将temp链表添加为curr的下一个元素。因此,我假设我得到了3->4->5->null。

但是,当我返回head元素时,我得到的是1->2->3->4->5->null。

这是如何工作的?curr和head都指向同一个对象,对吗?当我们更改curr时,head应该指向相同的对象。这是如何实现的?

英文:

I am building a Linked list here.

public ListNode addNode(ListNode head, ListNode temp){
    if(head == null){
        head = temp;
    } else{
        ListNode curr = head;
        while(curr.next != null){
        curr = curr.next;
        }
     curr.next = temp;
    }
    return head;
}

I have to merge two Linkedlist here.
For e.g. we assume head as 1->2->3->null, temp as 4->5->null, I need the output as 1->2->3->4->5->null

On the head list, we have to move to last node so that we can merge the temp list. To move the pointer to the last node of the head list, I am iterating till I get next element as null which means the curr list will have 3->null alone when the while loop exists. Then, I am adding the temp list as the next element of curr. So, I assume I get 3->4->5->null.

But, when I return head element, I am getting 1->2->3->4->5->null.

How this works> Both curr and head are pointing to same objects right? When we change curr, head should point to the same. How is this working?

huangapple
  • 本文由 发表于 2020年4月5日 17:31:12
  • 转载请务必保留本文链接:https://java.coder-hub.com/61040554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定