题解 | #复杂链表的复制#

复杂链表的复制

http://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba

/* public class RandomListNode { int label; RandomListNode next = null; RandomListNode random = null;

RandomListNode(int label) {
    this.label = label;
}

} */

import java.util.*;

public class Solution { public RandomListNode Clone(RandomListNode pHead) {

    HashMap<RandomListNode, RandomListNode> map = new HashMap();
    
    RandomListNode cur = pHead;
            //利用HashMap复制所有节点,value值只包括lable值,无指针
    while(cur != null){
        map.put(cur, new RandomListNode(cur.label));
        cur = cur.next;
    }
    //重置
    cur = pHead;
    //利用map中key的链表各节点的next和random指针,形成value中链表各节点的next和random指针,完成对复杂链表的深拷贝
    while(cur != null){
        map.get(cur).next = map.get(cur.next);
        map.get(cur).random = map.get(cur.random);
        cur = cur.next;
    }
    return map.get(pHead);
}

}

全部评论

相关推荐

球球别再泡了:坏,我单9要了14
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务