leetCode练习(138)

题目:Copy List with Random Pointer

难度:medium

问题描述:

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

解题思路:

难点在于random指针指向的节点可能还没有被构造。我们可以使用map来建立old和new链表节点的对应关系,然后通过DFS回溯复制节点。求解时需要注意自环的情况。

代码如下:

public class List_复制 {
	/*
	 * 复制一个带有额外指针的链表
	 */
	Map<RandomListNode,RandomListNode> map = new HashMap<>();
	public RandomListNode copyRandomList(RandomListNode head) {
            RandomListNode t = head;
            while(t!=null){
        	copy(t);
        	t=t.next;
            }
            return map.get(t);
        }
	private RandomListNode copy(RandomListNode t){
		if(t==null) return null;
		if(map.containsKey(t)){
			return map.get(t);
		}else{
			RandomListNode c = new RandomListNode(t.label);
            map.put(t,c);
			c.next = copy(t.next);
            if(t.random==t){	//防止自环
                c.random = c;
            }else{
                c.random = copy(t.random);
            }
			return c;
		}
	}
	class RandomListNode {
		 int label;
		 RandomListNode next, random;
		 RandomListNode(int x) { this.label = x; }
	}
	
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值