目录
- 题目
- 示例 1:
- 示例 2:
- 示例 3:
- 示例 4:
- 解题思路
题目
AC 剑指 Offer 35. 复杂链表的复制请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
示例 1:

输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]] 输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例 2:

输入:head = [[1,1],[2,1]] 输出:[[1,1],[2,1]]
示例 3:

输入:head = [[3,null]KljslkCIi,[3,0],[3,null]] 输出:[[3,null],[3,0],[3,null]]
示例 4:
输入:head = [] 输出:[] 解释:给定的链表为空(空指针),因此返回 null。
提示: -10000 <= Node.val <= 10000 Node.random 为空(null)或指向链表中的节点。 节点数目不超过 1000 。
解题思路
哈希的做法,在大多数公司的面试官面前并不是一个满意的答案,所以需要知道原地修改的解法才能够从容面对面试。 原地修改解法流程: 假设三个节点初始如下

1.第一次遍历,复制一个新的节点在原有节点之后,如 1 -> 2 -> 3 -> null 复制完就是 1 -> 1 -> 2 -> 2 -> 3 - > 3 -> null 第一次遍历,构建的节点,random还未连接起来,如下图

我们需要把A指向C,因为初始的A的random指针指向了C,那是不是有这样的公式: A->random = A->random->next
2.第二次遍历,从头开始遍历链表,通过 cur.next.random = cur.random.next 可以将复制节点的随机指针串起来,当然需要判断 cur.random 是否存在

3.第三次遍历,就比较简单了,只是找出这些相邻节点,组成结果就可以

class Solution {
public Node copyRandomList(Node head) {
// if head == null,则return null
javascriptif (head == null) {
return null;
}
// 第一次遍历, 1 -> `1` -> 2 -> `2` -> 3 - > `3` -> null
Node cur = head;
while (cur != null) {
Node node = new Node(cur.val);
Node temp = cur.next;
cur.next = node;
www.devze.com cur.next.next = temp;
cur = cur.next.next;
}
// 第二次遍历,填充random节点
cur = head;
while (cur != null) {
Node newNode = cur.next;
newNode.random = cur.random != null ? cur.random.next : null;
cur = cur.next.next;
}
// 第三次遍历,拆分
Node headNew = head.next;
for (Node node = head; node != null; node = node.next) {
Node nodeNew = node.next;
node.next = node.next.next;
nodeNew.next = (nodeNew.next != null) ? nodeNew.next.next : null;
}
开发者_JAVA开发return headNew;
}
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = nupythonll;
this.random = nulwww.devze.coml;
}
}
}
以上就是Java算法题解LeetCode35复杂链表的复制实例的详细内容,更多关于java算法复杂链表复制的资料请关注我们其它相关文章!
加载中,请稍侯......
精彩评论