题目描述
方法1:原链表复制拆解
解题思路
- 一次遍历: 复制各节点
- 二次遍历:构造相同random引用
- 三次遍历:拆解成两个链表
代码
/*
// 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 head;
}
Node cur = head;
// 将各节点在其后复制一个
while(cur != null) {
// 注意new的时候 Node值为cur.val
Node newNode = new Node(cur.val);
newNode.next = cur.next;
cur.next = newNode;
cur = newNode.next;
}
cur = head;
while(cur != null) {
// 如果rodom不为空,代表为原链表节点
if (cur.random != null){
/*左边 cur.next.random:新链表节点的random ,
**右边 cur.random.next:原链表节点的random的下个节点,该节点值和原链表节点的random引用值相同,但是属于新构造的链表
*注意不能使新链表的random指向原链表节点
*/
cur.next.random = cur.random.next;
}
cur = cur.next.next;
}
// 拆解链表,注意原链表要还原
cur = head.next;
Node prev = head;
Node copyNode = head.next;
//注意循环中有用到cur.next.next, 则终止条件为cur.next = null
while(cur.next != null) {
// 改变next指针指向
prev.next = prev.next.next;
cur.next = cur.next.next;
// 迭代遍历
prev = prev.next;
cur = cur.next;
}
// 循环终止时,cur.next已为null, 而prev.next还不是
prev.next = null;
return copyNode;
}
}
复杂度分析
时间复杂度:O(n)。三次遍历。
空间复杂度:O(1)。在原链表上进行操作。
方法2 HashMap
解题思路
- 循环遍历链表,储存新旧节点键值对。key 旧节点, value 新节点;
- 循环遍历链表,使新节点next引用指向旧节点的next;使新节点random引用指向旧节点的random;
代码实现
class Solution {
public Node copyRandomList(Node head) {
if(head == null) {
return head;
}
Node cur = head;
Map<Node, Node> map = new HashMap<>();
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);
}
}
复杂度分析
时间复杂度:O(n)。两次遍历。
空间复杂度:O(n)。Hashmap储存了同样大小的键值对。