Leetcode (copy List with Random pointer) deep copy of complex lists

Source: Internet
Author: User

Topic Requirements:


A linked list is given such, each node contains A additional random pointer which could point to any node in the list or null.

Return a deep copy of the list. Sword refers to the issue of the offer,

The idea is:

1. First point to the original linked list after each node, copy a new node, the original list of the length of twice times random pointer to the original linked table node random pointer to the node behind the node.

2. Split the list into two lists.


Code:

Class Solution {public:void copynodeandrandompointer (randomlistnode* head) {randomlistnode* node =
        Head
            while (NULL!= node) {randomlistnode* New_node = new Randomlistnode (Node->label);
            New_node->next = node->next;
            Node->next = New_node;
        node = new_node->next;
        }//set random pointer node = head;
            while (NULL!= node) {randomlistnode* Pnext = node->next;
            if (NULL!= node->random) {pnext->random = node->random->next;
        node = pnext->next;  } randomlistnode* seperatelist (randomlistnode* head) {randomlistnode* node = head, *clone_head
        = NULL, *clone_node = NULL;
            if (NULL!= node) {clone_head = Clone_node = node->next;
            Node->next = clone_node->next;
        node = node->next; } while (NULL!= node)
            {Clone_node->next = node->next;
            Clone_node = clone_node->next;
            Node->next = clone_node->next;
        node = node->next;
    return clone_head;
        } randomlistnode *copyrandomlist (Randomlistnode *head) {copynodeandrandompointer (head);
    Return Seperatelist (head); }
};


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.