当前位置:网站首页>Sword finger offer 35 Replication of complex linked list

Sword finger offer 35 Replication of complex linked list

2022-07-05 05:28:00 ThE wAlkIng D

Title Description

 Insert picture description here

Problem analysis ( Use HashMap To do it )

1. Judge whether it is empty first , If it is empty, return null
2. newly build map Set to copy the original list to the new list
3. Create a pointer to the new linked list

Code instance

/* // Definition for a Node. class Node { int val; Node next; Node random; public Node(int val) { this.val = val; this.next = null; this.random = null; } } */
class Solution {
    
    public Node copyRandomList(Node head) {
    
       if(head == null){
    
       		return null;
       }
       Node cur = head;
       Map<Node,Node> map = new HashMap<Node,Node>();
       while(cur != null){
    
       		Map.put(cur,new Node(cur.val));
       		cur = cur.next;
       }
       cur = head;
       while(cur != null){
    
       		Map.get(cur).next = Map.get(cur.next);
       		Map.get(cur).random = Map.get(cur.random);
       		cur = cur.next;
       }
       return Map.get(head);
    }
}
原网站

版权声明
本文为[ThE wAlkIng D]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050525449607.html