首页 > 其他 > 详细

Copy List with Random Pointer -- leetcode

时间:2015-06-01 13:22:14      阅读:135      评论:0      收藏:0      [点我收藏+]

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.


基本思路:

三趟扫描。

第一趟,复制节点。并将复制的节点,插入被复制节点后面。  第一趟完成后,就形成了,旧节点,复制节点,交错的一个链表。

第二趟,为复制节点的random指针解决引用。  

第三趟,将链表拆开。


在leetcode上实际执行时间为120ms。


/**
 * 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:
    RandomListNode *copyRandomList(RandomListNode *head) {
        RandomListNode fake(0);
        RandomListNode *p = &fake;
        while (head) {
            p->next = head;
            head = head->next;
            p->next->next = new RandomListNode(p->next->label);
            p = p->next->next;
        }
        
        p = fake.next;
        while (p) {
            if (p->random) {
                p->next->random = p->random->next;
            }
            p = p->next->next;
        }
        
        RandomListNode fake2(0);
        head = &fake2;
        p = fake.next;
        while (p) {
            head->next = p->next;
            head = head->next;
            p->next = p->next->next;
            p = p->next;
        }
        return fake2.next;
    }
};


Copy List with Random Pointer -- leetcode

原文:http://blog.csdn.net/elton_xiao/article/details/46301981

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!