LeetCode Copy List with Random Pointer

来源:互联网 发布:java code style 编辑:程序博客网 时间:2024/06/14 19:30

题目:

 A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list. 

题意:

将一个复杂单链表进行复制,注意:是复制,不是直接返回。

题解:

此题在《剑指offer》中出现了,面试题26,而且提供了3种方法来解决。其中我这里是采用了第三种方法。这种方法是不采用辅助空间来解决的,分三步来做。

第一步:根据原始链表的每个节点N创建对应的N’。然后我们把N’链接在N的后面。如下图所示:

 

    A ----> A' ----> B ----> B' ----> C ----> C' ----> D ----> D'.....

第二步:设置复制出来的节点的m_pSibiling,也就是指向不同的链。假设原始链表上的N的m_pSibiling指向节点S,那么对应复制出来的N’的next就指向S的next。


第三步:将这个单链表分拆成两个表,把奇数位置的节点用next连接起来的就是原始的链表,偶数位置连接起来的就是新复制出来的链表。

代码如下:

public RandomListNode copyRandomList(RandomListNode head){if(head == null)//这道题目,有点特别,如果碰到head.next == null的情况,也不能直接返回head,否则就会认为是直接返回的,所以哪怕只有一个节点,也必须要复制才能做return head;RandomListNode node = CloneNode(head);ConnectSiblingNodes(node);return ReconnectNodes(node);}public RandomListNode CloneNode(RandomListNode root){RandomListNode node = root;    while(node != null){RandomListNode pCloned = new RandomListNode(Integer.MIN_VALUE);    //首先这里要当心,因为不能复制,所以采用-1pCloned.label = node.label;pCloned.next = node.next;pCloned.random = null;node.next = pCloned;node = pCloned.next;}return root;}public void ConnectSiblingNodes(RandomListNode root){RandomListNode node = root;while(node != null){RandomListNode pCloned = node.next;if(node.random != null){pCloned.random = node.random.next;}node = pCloned.next;}}public RandomListNode ReconnectNodes(RandomListNode root){RandomListNode node = root;RandomListNode pClonedHead = null;RandomListNode pClonedNode = null;if(node != null){pClonedHead = pClonedNode = node.next;node.next = pClonedNode.next;node = node.next;}while(node != null){pClonedNode.next = node.next;pClonedNode = pClonedNode.next;node.next = pClonedNode.next;node = node.next;}return pClonedHead;}


0 0