Copy List with Random Pointer

来源:互联网 发布:特朗普 金正恩 知乎 编辑:程序博客网 时间:2024/06/11 23:01

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.

深拷贝链表。


Step 1: 首先指向在原链表的每个节点后面,复制一个新的节点,原链表长度变为 2 倍,

random 指针指向的是 原链表节点 random 指针指向的节点的后面的那个节点

Step 2: 将链表拆成两个 lists


\



RandomListNode *copyRandomList(RandomListNode *head){    if (head == NULL)        return NULL;    RandomListNode *pos1 = head, *pos2 = head->next;    while (pos1 != NULL)//add new list2 into    {        pos1->next = new RandomListNode(pos1->label);        pos1->next->next = pos2;        pos1 = pos2;        if (pos2 != NULL)            pos2 = pos2->next;    }    pos1 = head;    pos2 = head->next;    while (pos1 != NULL)//build random pointer for list2    {        if (pos1->random == NULL)            pos2->random = NULL;        else            pos2->random = pos1->random->next;        pos1 = pos1->next->next;        if (pos2->next != NULL)            pos2 = pos2->next->next;    }    RandomListNode *res = head->next;    pos1 = head, pos2=head->next;    while(pos2->next != NULL)//apart list1 and list2    {        pos1->next = pos2->next;        pos1 = pos2;        pos2 = pos2->next;    }    pos1->next = NULL;    return res;}


0 0
原创粉丝点击