Copy List with Random Pointers

复制带随机指针的链表

思路1:使用哈希表,需要消耗O(N)的额外空间。

 1 public class Solution {
 2     /**
 3      * @param head: The head of linked list with a random pointer.
 4      * @return: A new head of a deep copy of the list.
 5      */
 6     public RandomListNode copyRandomList(RandomListNode head) {
 7         // write your code here
 8         
 9         Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
10         RandomListNode cur = head;
11         RandomListNode copyDummy = new RandomListNode(0);
12         RandomListNode copyCur = copyDummy;
13         
14         while (cur != null) {
15             copyCur.next = new RandomListNode(cur.label);
16             copyCur = copyCur.next;
17             map.put(cur, copyCur);
18             cur = cur.next;
19         }
20         
21         cur = head;
22         while (cur != null) {
23             copyCur = map.get(cur);
24             copyCur.random = map.get(cur.random);
25             cur = cur.next;
26         }       
27         return copyDummy.next;
28     }
29 }
View Code

相关文章:

  • 2021-11-15
  • 2021-05-15
  • 2021-11-06
  • 2022-12-23
  • 2021-10-29
  • 2022-12-23
  • 2022-12-23
  • 2021-04-05
猜你喜欢
  • 2021-06-05
  • 2021-06-19
  • 2022-02-11
  • 2021-07-20
  • 2021-12-01
  • 2021-09-30
相关资源
相似解决方案