链表----复制含有随机指针的链表

 

关键点:

  • 方法1:利用hashmap
  • 方法2:利用指针

代码 

	public static Node copyList1(Node head) {
		if(head == null) return null;
		//1、准备一个HashMap <key,value> <节点,该节点的副本>
		HashMap<Node,Node> map = new HashMap<Node, Node>();
		Node cur = head;
		while(cur != null) {
			map.put(cur, new Node(cur.value));
			cur = cur.next;	
		}
		//2、复制next指针和rand随机指针
		cur = head;
		while(cur != null) {
			map.get(cur).next = cur.next;
			map.get(cur).rand = cur.rand;
			cur = cur.next;
		}
		return map.get(head);
		
	}
	
	public static Node copyList2(Node head) {
		if(head == null) return null;
		//1、复制节点 1-->2-->3-->  ==> 1-->1'-->2-->2'-->3-->3'-->
		Node cur = head;
		Node next = null;
		while(cur != null) {
			Node cpCur = new Node(cur.value);
			next = cur.next;
			cur.next = cpCur;
			cpCur.next = next;
			cur = next;	
		}
		//2、复制随机指针
		cur = head;
		Node cpCur = null;
		while(cur != null) {
			cpCur = cur.next;
			
			cpCur.rand= cur.rand == null ? null : cur.rand.next;
			
			cur = cur.next.next;	
		}
		//3、拆解链表 1-->1'-->2-->2'-->3-->3'-->  ==> 1-->2-->3--> + 1'-->2'-->3'-->
		cur = head;
		Node cpHead = cur.next;	
		while(cur != null) {
			cpCur = cur.next;
			next = cur.next.next;
			
			cur.next = next;
			cpCur.next = next == null ? null : next.next;
		
			cur = next;
		}
		return cpHead;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值