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

Copy List with Random Pointer

时间:2014-08-10 03:53:09      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   strong   for   div   html   

类同:剑指 Offer 题目汇总索引第26题

Copy List with Random Pointer

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.

说明:分三步, 1. 每个节点复制其本身并链接在后面。 2, 复制随机指针。 3, 拆分链表。

/**
 * 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) {
        if(head == NULL) return NULL;
        RandomListNode *head2, *p, *p2;
        p = head2 = head;
        while(p) {
            RandomListNode *s = new RandomListNode(p->label);
            s->next = p->next;
            p->next = s;
            p = s->next;
        }
        p = head;
        while(p) {
            if(p->random) p->next->random = p->random->next;
            p = p->next->next;
        }
        head2 = p2 = head->next; p = head;
        while(p) {
            p->next = p->next->next;
            p = p->next;
            if(p2->next) {
                p2->next = p2->next->next;
                p2 = p2->next;
            }
        }
        return head2;
    }
};

 

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

Copy List with Random Pointer

标签:style   blog   http   io   strong   for   div   html   

原文地址:http://www.cnblogs.com/liyangguang1988/p/3902302.html

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