为什么对新链表操作会改变原链表的值

新建一个链表head,然后对链表进行赋值。
ListNode [val=1, next=ListNode [val=2, next=ListNode [val=3, next=null]]]
ListNode temp =head; 对temp 赋值然后对temp 操作 head 也会随之改变。

 public class ListNode {
   int val;
   ListNode next;
   ListNode() {}
   ListNode(int val) { this.val = val; }
   ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  @Override
   public String toString() {
	  return "ListNode [val=" + val + ", next=" + next + "]";
      }
 }

测试

    public static void main(String[] args) {
	  //第一个节点
	  ListNode head =new ListNode(1);
	  //第二个节点
	  ListNode cont1 = new ListNode(2);
	  //第一个节点的指针指向下一个节点
	  head.next = cont1;
	  //第三个节点
	  ListNode cont2 = new ListNode(3);
	  cont1.next = cont2;
	  ListNode temp =head;
	  System.out.println("temp的值:"+temp);
	  System.out.println("temp的hash值:"+temp.hashCode());
	  System.out.println("head的值:"+head);
	  System.out.println("head的hash值:"+head.hashCode());
  }

输出:

  temp的值:ListNode [val=1, next=ListNode [val=2, next=ListNode [val=3, next=null]]]
  temp的hash值:366712642
  head的值:ListNode [val=1, next=ListNode [val=2, next=ListNode [val=3, next=null]]]
  head的hash值:366712642

研究明白,原链表head是储存在堆内存中,temp = head,只是将temp和head具有同一个引用地址,后续对temp的操作,即也是对这个引用地址中数据的操作,故原head数据也会改变。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值