Offer.P35[复杂链表的复制] 方法一:哈希表1234567891011121314151617181920212223242526272829303132/*// 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 p = head; Map<Node, Node> map = new HashMap<>(); while (p != null) { map.put(p, new Node(p.val)); p = p.next; } p = head; while (p != null) { map.get(p).next = map.get(p.next); map.get(p).random = map.get(p.random); p = p.next; } return map.get(head); }} 时间复杂度:$O(n)$ 空间复杂度:$O(n)$ 方法二:拼接+拆分12345678910111213141516171819202122232425262728293031323334353637383940414243444546/*// 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; // 复制各节点,并构建新链表 while (cur != null) { Node temp = new Node(cur.val); temp.next = cur.next; cur.next = temp; cur = temp.next; } cur = head; // 构建新链表的random指向 while (cur != null) { if (cur.random != null) { cur.next.random = cur.random.next; } cur = cur.next.next; } // 拆分链表 cur = head.next; Node pre = head, ans = head.next; while (cur.next != null) { pre.next = pre.next.next; cur.next = cur.next.next; pre = pre.next; cur = cur.next; } pre.next = null; return ans; }} 时间复杂度:$O(n)$ 空间复杂度:$O(1)$