来源:剑指 Offer 35. 复杂链表的复制/*// 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; /* 1. 复制各节点,并构建拼接链表 * 插入节点常规操作,注意cur = tmp.next; */ while(cur != null) { Node tmp = new Node(cur.val); tmp.next = cur.next; cur.next = tmp; cur = tmp.next; } /* 2. 构建各新节点的 random 指向 * 复制节点的random与原节点指向同一个 */ cur = head; while(cur != null) { if(cur.random != null) cur.next.random = cur.random.next; cur = cur.next.next; } /* 3. 拆分两链表 * cur是用来找复制点的 * pre是用来找原节点的 * res指向复制点的头,用来输出复制点的 */ cur = head.next; Node pre = head, res = 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 res; // 返回新链表头节点 }}