0
点赞
收藏
分享

微信扫一扫

Java实现复杂链表的复制

艾晓雪 2022-01-31 阅读 68
Java实现复杂链表的复制

过程很简单,直接上代码

import java.util.HashMap;
import java.util.Map;

public class Solution {
	
	/**
	 * 复杂链表复制
	 * @param pHead
	 * @return
	 */
    public RandomListNode Clone(RandomListNode pHead) {
    	
    	Map<RandomListNode,RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
    	RandomListNode currentNode = pHead;

    	// 复制节点中的属性
    	while (currentNode != null) {
    		map.put(currentNode, new RandomListNode(currentNode.label));
    		currentNode = currentNode.next;
    	}
    	
    	
    	// 复制节点中的关系
    	currentNode = pHead;
    	while (currentNode != null) {
    		map.get(currentNode).next = map.get(currentNode.next);
    		map.get(currentNode).random = map.get(currentNode.random);
    		currentNode = currentNode.next;
    	}
    	
    	return map.get(pHead);
        
    }
}
举报

相关推荐

0 条评论