Copy List with Random Pointer--leetcode

Source: Internet
Author: User

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.


This is a list operation topic, requires copying a linked list, but each node of the list with a random pointer to a node point.
We first introduce a more straightforward algorithm, the idea is to copy a normal linked list, copy the copy of the node to do a hashmap, the old node as the key, the new node is value. The purpose of this is to use the hash table to connect the random pointers of the nodes to the second scan. This algorithm is relatively easy to think of, a total of two scans, so the time complexity is O (2*n) =o (n). Space requires a hash table to do the mapping of nodes, so the spatial complexity is also O (n). The code is as follows:

Public Randomlistnode copyrandomlist (Randomlistnode head) {if (head = = null) return head;          hashmap<randomlistnode,randomlistnode> map = new hashmap<randomlistnode,randomlistnode> ();          Randomlistnode newhead = new Randomlistnode (Head.label);          Map.put (Head,newhead);          Randomlistnode pre = Newhead;          Randomlistnode node = head.next;              while (node!=null) {Randomlistnode NewNode = new Randomlistnode (Node.label);              Map.put (Node,newnode);              Pre.next = NewNode;              Pre = NewNode;          node = Node.next;          } node = head;          Randomlistnode Copynode = Newhead;              while (node!=null) {copynode.random = Map.get (node.random);              Copynode = Copynode.next;          node = Node.next;      } return newhead; }


Copy List with Random pointer--leetcode

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.