leetcode#138 Copy List with Random Pointer

Source: Internet
Author: User

Original title Address

A very ingenious approach that does not require a map and requires only O (1) of additional storage space, divided into 3 steps:

1. Copy the linked list first, but this replication is special, each newly-replicated node is added to the back of the original node, which is equivalent to the "stopper"
2. Construct the random pointer of the new node based on the Ramdon pointer of the original node
3. Restore the original linked list structure while getting a new copy of the linked list

Time complexity: O (N)

Note that the random may be null

Code:

1Randomlistnode *copyrandomlist (Randomlistnode *head) {2Randomlistnode *h =NULL;3 4h =head;5    while(h) {6Randomlistnode *node =NewRandomlistnode (h->label);7Node->next = h->Next;8H->next =node;9H = h->next->Next;Ten   } One  Ah =head; -    while(h) { -H->next->random = H->random? H->random->Next:null; theH = h->next->Next; -   } -  -h = head? Head->Next:null; +    while(head) { -Randomlistnode *tmp = head->Next; +Head->next = head->next->Next; ATmp->next = Head->next? Head->next->Next:null; atHead = head->Next; -   } -  -   returnh; -}

leetcode#138 Copy List with Random Pointer

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.