【LeetCode】剑指 Offer 35. 复杂链表的复制

【LeetCode】剑指 Offer 35. 复杂链表的复制

文章目录

【LeetCode】剑指 Offer 35. 复杂链表的复制
【LeetCode】剑指 Offer 35. 复杂链表的复制

package offer;

import java.util.ArrayList;
import java.util.HashMap;

//定义节点
class Node{
    int value;
    Node next;
    Node random;
    public Node(int value){
        this.value = value;
        this.next = null;
        this.random = null;
    }

    @Override
    public String toString() {
        return "["+ value +","+ random +"]";
    }
}

public class Solution35 {
    public static void main(String[] args) {
        Node node1 = new Node(3);
        Node node2 = new Node(3);
        Node node3 = new Node(3);
        node1.next = node2;
        node2.next = node3;
        node2.random = node1;
        Solution35 solution = new Solution35();
        Node result = solution.method(node1);
        while(result != null){
            System.out.print(result);
            if(result.next != null){
                System.out.print(",");
            }
            result = result.next;
        }
    }

    private Node method(Node head){
        if(head == null) return null;

        HashMap<Node, Node> map = new HashMap<>();
        Node cur = head;

        //将原节点和新节点的映射存入 HashMap
        while(cur != null){
            map.put(cur, new Node(cur.value));
            cur = cur.next;
        }

        cur = head;

        //为新节点的 next 和 random 赋值
        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);
    }
}

//时间复杂度为 O(n)
//空间复杂度为 O(1)
上一篇:为方便大家食用小鱼Moveit2相关教程|解决Moveit2更新不稳定问题|小鱼已将源码打包


下一篇:ROS2入门教程-windows安装ROS2