【重点】138.随机链表的复制

该代码展示了如何在Java中实现一个名为`copyRandomList`的方法,用于复制一个具有随机指针的链表,通过创建映射并保持原链表和复制链表之间的关系。

题目

Python

"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""

class Solution:
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
        if not head:
            return head
        node_map = dict()
        cur = head
        while cur:
            node_map[cur] = Node(cur.val)
            cur = cur.next
        cur = head
        while cur:
            node_map[cur].next = node_map[cur.next] if cur.next else None
            node_map[cur].random = node_map[cur.random] if cur.random else None
            cur = cur.next
        
        return node_map[head]
"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""

class Solution:
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
        if head == None:
            return head

        cur = head
        while cur != None:
            next_node = cur.next
            new_node = Node(cur.val, None, None)
            cur.next = new_node
            new_node.next = next_node
            cur = next_node
        cur = head
        while cur != None:
            cur.next.random = None if cur.random == None else cur.random.next
            cur = cur.next.next
        
        cur = head.next
        while cur != None:
            next_node = cur.next
            cur.next = None if next_node == None else next_node.next
            cur = cur.next

        return head.next

Java

class Solution {
    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        Map<Node, Node> toRandomMap = new HashMap<>();
        Map<Node, Node> originToCopyMap = new HashMap<>();
        Node cur = head;
        while (cur != null) {
            if (cur.random != null) {
                toRandomMap.put(cur, cur.random);
            }
            originToCopyMap.put(cur, new Node(cur.val));
            cur = cur.next;
        }
        cur = head;
        while (cur != null) {
            Node next = cur.next == null ? null : originToCopyMap.get(cur.next);
            Node random = cur.random == null ? null : originToCopyMap.get(cur.random);
            originToCopyMap.get(cur).next = next;
            originToCopyMap.get(cur).random = random;
            cur = cur.next;
        }

        return originToCopyMap.get(head);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值