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 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; }
	}
	
}



你可能感兴趣的:(leetCode)