剑指offer面试题35:复杂链表的复制(Java 实现)

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

思路:

  1. 根据原链表中每个节点N创建对应的新节点N’。并把N’链接到N的后面。
  2. 设置复制出来的节点的random节点。假设N的random指向节点S,因为N’是N的下一个节点,所以S’也应该为S的下一个节点。
  3. 把链表拆分。奇数位置的节点链接起来就是原始的链表。偶数位置的节点链接起来,就是新复制后的链表。

测试用例:

  1. 功能测试:节点中的random节点指向节点自身;两个节点的random节点形成环状结构;链表中只有一个节点。
  2. 特殊测试:输入的链表头结点为空。
public class test_thirty_five {
    public RandomListNode Clone(RandomListNode pHead){
        if (pHead == null)return null;

        //定义当前节点的头结点
        RandomListNode pCurrent = pHead;

        //遍历复制当前链表的每一个节点A',并把A'连接到A后面,A-A'-B-B'-C-C'
        while (pCurrent != null){
            RandomListNode pClone = new RandomListNode(pCurrent.label);
            pClone.next = pCurrent.next;
            pCurrent.next = pClone;
            //遍历复制前链表的下一个节点
            pCurrent = pClone.next;
        }
        //更新当前链表为复制后的新链表
        pCurrent = pHead;

        //设置复制出来的节点的random节点
        while (pCurrent != null){
            if (pCurrent.random != null){       //如果当前节点有任意节点
                //复制后节点的任意节点等于复制前的任意节点的下一个
                pCurrent.next.random = pCurrent.random.next;
            }
            //遍历复制前链表的每一个节点,跳掉复制后的节点
            pCurrent = pCurrent.next.next;
        }
        //再次更新当前链表
        pCurrent = pHead;

        //把链表拆分为两个链表
        RandomListNode head = pHead.next;  //定义复制后的链表的头结点
        RandomListNode clone = head;

        while (pCurrent != null){
            //依次遍历然后往前覆盖就可以了
            pCurrent.next = pCurrent.next.next;   //覆盖掉复制后的节点得到复制前的链表
            if (clone.next != null){
                clone.next = clone.next.next;     //覆盖掉复制前的节点得到复制后的链表
            }
            clone = clone.next;
            pCurrent = pCurrent.next;
        }
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41163113/article/details/86571555