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

【leetcode】Copy List with Random Pointer (hard)

时间:2015-03-03 20:20:36      阅读:129      评论: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位置,再拆分两个链表。

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;


// 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 * p = head;

        //在每个结点后面复制一个自己 不管random指针
        while(p != NULL)
        {
            RandomListNode * cpy = new RandomListNode(p->label);
            cpy->next = p->next;
            p->next = cpy;

            p = cpy->next;
        }

        //复制random指针
        p = head;
        while(p != NULL)
        {
            RandomListNode * cpy = p->next;
            if(p->random != NULL)
            {
                cpy->random = p->random->next;
            }

            p = cpy->next;
        }

        //把原链表与复制链表拆开
        RandomListNode * cpyhead = head->next;
        p = head;
        RandomListNode * cpy = cpyhead;
        while(p != NULL)
        {
            p->next = cpy->next;
            cpy->next = (cpy->next == NULL) ? cpy->next : cpy->next->next;

            p = p->next;
            cpy = cpy->next;
        }

        return cpyhead;
    }
};

int main()
{
    RandomListNode * r = new RandomListNode(-1);
    Solution s;
    RandomListNode * ans = s.copyRandomList(r);

    return 0;
}

 

【leetcode】Copy List with Random Pointer (hard)

标签:

原文地址:http://www.cnblogs.com/dplearning/p/4311731.html

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