美文网首页剑指 Offer Java版
剑指Offer Java版 面试题35:复杂链表的复制

剑指Offer Java版 面试题35:复杂链表的复制

作者: 孙强Jimmy | 来源:发表于2019-07-21 15:24 被阅读6次

题目:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。

练习地址

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

参考答案

/*
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;
        }
        cloneNodes(pHead);
        connectRandomNodes(pHead);
        return reconnectNodes(pHead);
    }
    
    private void cloneNodes(RandomListNode head) {
        // 根据原始链表的每个节点N创建对应的N'
        RandomListNode node = head;
        while (node != null) {
            RandomListNode cloned = new RandomListNode(node.label);
            cloned.next = node.next;
            node.next = cloned;
            node = cloned.next;
        }
    }
    
    private void connectRandomNodes(RandomListNode head) {
        // 设置复制出来的节点的random
        RandomListNode node = head, cloned;
        while (node != null) {
            cloned = node.next;
            if (node.random != null) {
                cloned.random = node.random.next;
            }
            node = cloned.next;
        }
    }
    
    private RandomListNode reconnectNodes(RandomListNode head) {
        // 把这个长链表拆分成两个链表
        RandomListNode node = head, clonedHead = head.next, cloned;
        while (node != null) {
            cloned = node.next;
            node.next = cloned.next;
            if (node.next != null) {
                cloned.next = node.next.next;
            }
            node = node.next;
        }
        return clonedHead;
    }
}

复杂度分析

  • 时间复杂度:O(n)。
  • 空间复杂度:O(1)。

👉剑指Offer Java版目录
👉剑指Offer Java版专题

相关文章

网友评论

    本文标题:剑指Offer Java版 面试题35:复杂链表的复制

    本文链接:https://www.haomeiwen.com/subject/hbamlctx.html