剑指offer----复杂链表的复制

题目:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

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

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

复制拆分

public class Solution {
    public RandomListNode Clone(RandomListNode pHead)
    {
        if(pHead == null){
            return null;
        }
        RandomListNode curr = pHead;
        while(curr != null){
            RandomListNode node = new RandomListNode(curr.label);
            node.next = curr.next;
            curr.next = node;
            curr = node.next;
        }
        curr = pHead;
        while(curr != null){
            if(curr.random != null){
                curr.next.random = curr.random.next;
            }
            curr = curr.next.next;
        }

        curr = pHead.next;
        RandomListNode head = curr;
        while(pHead != null){
            pHead.next = curr.next;
            pHead = pHead.next;
            if(pHead != null){
                curr.next = pHead.next;
                curr = curr.next;
            }
        }
        return head;
    }
}
第一轮遍历:

依次复制节点,并将复制后的节点以此放到被复制的节点的后面,重新组成一个链表
A->B->C ------>> A->A'->B->B'->C->C'
此时只赋值next的指针

第二轮遍历

更新每一个复制节点的random指针,由于每个节点都是成对出现的,所以复制节点的random在被复制节点的random的next

第三轮遍历

将链表拆开,并返回头结点。


hashmap + 递归

import java.util.HashMap;
public class Solution {
    HashMap<RandomListNode, RandomListNode> hash = new HashMap<>();
    public RandomListNode Clone(RandomListNode pHead)
    {
        if(pHead == null){
            return null;
        }
        RandomListNode node = new RandomListNode(pHead.label);
        hash.put(pHead, node);
        node.next = Clone(pHead.next);
        node.random = hash.get(pHead.random);
        return node;
    }
}

在next不断递归时利用HashMap将节点对应,然后random对应更新。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容