码迷,mamicode.com
首页 > 其他好文 > 详细

Copy List with Random Pointer

时间:2014-05-15 21:00:06      阅读:325      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   class   code   java   

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.

思路:这题的关键是如何定位next和random。

1.根据原始链表的每个结点N创建对应的克隆结点N‘,并且把N‘链接在N的后面;

2.设置复制出来的结点的random,假设原始链表上的N的random指向结点S,对应其复制出来的N‘是N的next指向的结点,同样S‘也是S的random指向的结点。也就是如果原始链表上的结点N的random指向S,则它对应的复制结点N‘的random指向S的下一节点S‘;

3.把这个长链表拆分成两个链表:把奇数位置的结点用next连接起来就是原始链表,把偶数位置的结点用next连接起来成为复制出来的结点。

bubuko.com,布布扣
/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     RandomListNode *next, *random;
 *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 * };
 */
class Solution {
public:
    void CloneNodes(RandomListNode *pHead)
    {
        RandomListNode *pNode=pHead;
        while(pNode!=NULL)
        {
            RandomListNode *pCloned=new RandomListNode(pNode->label);
            //pCloned->label=pNode->label;
            pCloned->next=pNode->next;
            pCloned->random=NULL;
            pNode->next=pCloned;
            pNode=pCloned->next;
        }
    }
    void ConnectRandomNodes(RandomListNode *pHead)
    {
        RandomListNode *pNode=pHead;
        while(pNode!=NULL)
        {
            RandomListNode *pCloned=pNode->next;
            if(pNode->random!=NULL)
            {
                pCloned->random=pNode->random->next;
            }
            pNode=pCloned->next;
        }
    }
    RandomListNode *ReconnectNodes(RandomListNode *pHead)
    {
        RandomListNode *pNode=pHead;
        RandomListNode *pClonedHead=NULL;
        RandomListNode *pClonedNode=NULL;
        if(pNode!=NULL)
        {
            pClonedHead=pClonedNode=pNode->next;
            pNode->next=pClonedNode->next;
            pNode=pNode->next;
        }
        while(pNode!=NULL)
        {
            pClonedNode->next=pNode->next;
            pClonedNode=pClonedNode->next;
            pNode->next=pClonedNode->next;
            pNode=pNode->next;
        }
        return pClonedHead;
    }
    RandomListNode *copyRandomList(RandomListNode *head) {
        CloneNodes(head);
        ConnectRandomNodes(head);
        ReconnectNodes(head);
    }
};
bubuko.com,布布扣

 

Copy List with Random Pointer,布布扣,bubuko.com

Copy List with Random Pointer

标签:des   style   blog   class   code   java   

原文地址:http://www.cnblogs.com/awy-blog/p/3729751.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!