138. Copy List with Random Pointer(unsolved)

来源:互联网 发布:sharp扫描软件 编辑:程序博客网 时间:2024/06/08 19:22

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.

思路:
step1: 复制l1链表中的每个节点分别连接到该节点自身的后面。如1->1->2->2->4->4->3->3->null

step2:每一个原节点后面的那个节点,即拷贝的节点,复制原节点的random的next,因为是要复制整条链表。

step3:拆分两条链表。分别对l1,l2操作

/** * 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 *newHead, *l1, *l2;        if (head == NULL) return NULL;        for (l1 = head; l1 != NULL; l1 = l1->next->next) {            l2 = new RandomListNode(l1->label);            l2->next = l1->next;            l1->next = l2;        }        newHead = head->next;        for (l1 = head; l1 != NULL; l1 = l1->next->next) {            if (l1->random != NULL) l1->next->random = l1->random->next;        }        for (l1 = head; l1 != NULL; l1 = l1->next) {            l2 = l1->next;            l1->next = l2->next;            if (l2->next != NULL) l2->next = l2->next->next;        }        return newHead;    }};
0 0