Lintcode-medium-copy List with Random Pointer

Source: Internet
Author: User
Tags lintcode

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

Return a deep copy of the list.

Ideas:

First, according to the normal order, to get a copy of the linked list, while using a hashmap to establish the corresponding relationship between the old and new nodes, and then add the random pointer, so that the random pointer point to the node is always a new node has been established, will not be null

/*** Definition for singly-linked list with a random pointer. * Class Randomlistnode {* int label; * Randomlist Node Next, Random; * Randomlistnode (int x) {This.label = x;}}; */ Public classSolution {/**     * @paramhead:the head of linked list with a random pointer. * @return: A new head of a deep copy of the list. */     PublicRandomlistnode copyrandomlist (Randomlistnode head) {//Write your code here        if(Head = =NULL)            return NULL; Randomlistnode Newhead=NewRandomlistnode (Head.label); Randomlistnode P1=Head.next; Randomlistnode P2=Newhead; HashMap<randomlistnode, randomlistnode> map =NewHashmap<randomlistnode, randomlistnode>();                Map.put (head, newhead);  while(P1! =NULL) {P2.next=NewRandomlistnode (P1.label); P2=P2.next;            Map.put (P1, p2); P1=P1.next; } p1=Head; P2=Newhead;  while(P1! =NULL) {P2.random=Map.get (p1.random); P1=P1.next; P2=P2.next; }                returnNewhead; }}

Lintcode-medium-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.