剑指offer——复杂链表的复制_

来源:互联网 发布:双序列比对算法 编辑:程序博客网 时间:2024/05/23 15:08

题目描述

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


原思路:(通过不了)

1.将原链表复制一份(不加random),因为从前往后复制的,random若指向后面的结点 可能还没有造出来。

2.将整个链表遍历,给它加上random,通过Search(找到跟他label匹配的)。错误的地方在这里,测试的用例中,label有重复的,该种思路无法解题。

贴下代码:

/*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 result = new RandomListNode(-1);        RandomListNode p = result;        RandomListNode q = pHead;        while(q!=null){        RandomListNode temp = new RandomListNode(q.label);        p.next = temp;        p = p.next;        q = q.next;        }        p = result.next;        q = pHead;        while(p!=null||q!=null){        if(q.random!=null){        p.random = SearshRandomListNode(result, q.label);        }        q = q.next;        p = p.next;        }                return result.next;    }         public RandomListNode SearshRandomListNode(RandomListNode pHead,int label){ RandomListNode p = pHead; while(p!=null){ if(p.label==label) return p; p=p.next; }//while return null; }}
测试用例:



正确思路:

 1、复制每个节点,如:复制节点A得到A1,将A1插入节点A后面
 2、遍历链表,A1->random = A->random->next;
 3、将链表拆分成原链表和复制后的链表

/*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 q = pHead;        while(q!=null){        RandomListNode temp = new RandomListNode(q.label);        temp.next = q.next;        q.next = temp;        q = temp.next;        }        q = pHead;                while(q!=null){        RandomListNode temp = q.next;        if(q.random!=null){        temp.random = q.random.next;        }        q = temp.next;        }        //拆分        RandomListNode result = pHead.next;        q = pHead;        while(q.next!=null){        RandomListNode temp = q.next;        q.next = temp.next;        q = temp;        }        return result;    }}



原创粉丝点击