题目描述

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

题目链接:https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba?tpId=13&tqId=11178&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

 

分析:

 

注意,原来的链表也要分离出来,虽然不是题目要求,但是既然是复制,肯定是要额外的一条链表,不能破坏原来链表。

AC代码:

/*
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 p = pHead;
        while (p != null) {
            RandomListNode node = new RandomListNode(p.label);
            node.next = p.next;
            p.next = node;
            p = node.next;
        }
        p = pHead.next;
        RandomListNode last = pHead;
        while (p != null) { // 可能random指向自己,或者一个不在链表中的结点
            p.random = last.random == null ? null : last.random.next;
            last = p.next;
            p = last == null ? null : last.next;
        }
        RandomListNode curHead = pHead.next;
        last = pHead;
        p = curHead;
        while (p!= null) {
            last.next = p.next;
            last = p.next;
            p.next = last == null ? null : last.next;
            p = p.next;
        }
        return curHead;
    }
}

测试点可能为{1,2,3,4,5,3,5,#,2,#} ,#代表null,链表可能1-2-3-4-5-3-5,#,2,#,这3个结点可能是非链表结点,但是是random指向的结点。

 

========================Talk is cheap, show me the code=======================