1. 普通 / 复杂链表的复制

2. 题解
解题思路:
普通链表的节点定义如下:
class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
this.next = null;
}
}
本题链表的节点定义如下:
class Node {
int val;
Node next, random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
普通链表的复制很简单:
- 只需遍历链表,每轮建立新节点 + 构建前驱节点 pre 和当前节点 node 的引用指向即可。
class Solution {
public Node copyRandomList(Node head) {
Node cur = head;
Node dum = new Node(0), pre = dum;
while(cur != null) {
Node node = new Node(cur.val); // 复制节点 cur
pre.next = node; // 新链表的 前驱节点 -> 当前节点
// pre.random = "???"; // 新链表的 「 前驱节点 -> 当前节点 」 无法确定
cur = cur.next; // 遍历下一节点
pre = node; // 保存当前新节点
}
return dum.next;
}
}
(1) 哈希表
- 构建原节点和新节点的映射关系
- 每个节点都有一个映射,映射后节点指向构建完毕后
- 返回映射头结点即可
时间复杂度:O(n) 空间复杂度:O(n)
/*
// 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;
Map<Node, Node> map = new HashMap<>();
// 1. 复制各节点,并建立 “原节点 -> 新节点” 的 Map 映射
Node cur = head;
while (cur != null) {
map.put(cur, new Node(cur.val));
cur = cur.next;
}
// 2. 构建新链表的 next 和 random 指向
cur = head;
while (cur != null) {
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
// 3. 返回新链表的头节点
return map.get(head);
}
}
(2) 拼接 + 拆分
- 构建 原节点 1 -> 新节点 1 -> 原节点 2 -> 新节点 2 -> …… 的拼接链表,如此便可在访问原节点的 random 指向节点的同时找到新对应新节点的 random 指向节点。
时间复杂度:O(n) 空间复杂度:O(1)
/*
// 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;
// 1.拼接链表
Node cur = head;
while (cur != null) {
Node temp = new Node(cur.val);
temp.next = cur.next;
cur.next = temp;
cur = temp.next;
}
// 2.构建random指向
cur = head;
while (cur != null) {
if (cur.random != null)
cur.next.random = cur.random.next; //找到random的复制节点
cur = cur.next.next; //找到,下一个复制节点
}
// 3.拆分链表
cur = head.next; //复制链表头(用于标记移动链表)
Node pre = head; //原链表头
Node 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; //返回新链表头节点
}
}
版权声明:本文为ly0724ok原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。