leetcode算法题--复杂链表的复制

原题链接:https://leetcode.cn/problems/fu-za-lian-biao-de-fu-zhi-lcof/description/?envType=study-plan-v2&envId=coding-interviews

感觉一开始想到的办法还是比较笨

/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Next *Node
 *     Random *Node
 * }
 */

func copyRandomList(head *Node) *Node {
    if head == nil {
        return nil
    }
    res := &Node{}
    p1 := head
    p2 := res
    mp1 := make(map[*Node]int)
    mp22 := make(map[int]*Node)
    idx := 0
    for p1!= nil {
        p2.Val = p1.Val
        if p1.Next != nil {
            p2.Next = &Node{}
        }
        mp1[p1] = idx
        mp22[idx] = p2
        idx++
        p1 = p1.Next
        p2 = p2.Next
    }
    p1 = head
    p2 = res
    for p1 != nil {
        if p1.Random != nil {
            if idx, ok := mp1[p1.Random]; ok{
                p2.Random = mp22[idx] 
            } 
        }
        p1 = p1.Next
        p2 = p2.Next
    }
    return res
}

用回溯方法做

/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Next *Node
 *     Random *Node
 * }
 */

var cache = make(map[*Node]*Node)

func copyRandomList(head *Node) *Node {
    return deepCopy(head)
}

func deepCopy(head *Node) *Node {
    if head == nil {
        return nil
    }

    if node, ok := cache[head]; ok {
        return node 
    }

    newNode := &Node{}
    newNode.Val = head.Val
    cache[head] = newNode
    newNode.Next = deepCopy(head.Next)
    newNode.Random = deepCopy(head.Random)
    return newNode 
}

节点拆分法

/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Next *Node
 *     Random *Node
 * }
 */

func copyRandomList(head *Node) *Node {
    if head == nil {
        return nil
    }
    
    for node := head; node != nil; node = node.Next.Next {
        newNode := &Node{
           Val: node.Val, 
           Next: node.Next,
        }
        node.Next = newNode 
    }

    for node := head; node != nil; node = node.Next.Next {
        if node.Random != nil {
            newNode := node.Next
            newNode.Random = node.Random.Next 
        }
    }
    
    res := head.Next
    for node := head; node != nil; node = node.Next {
        newNode := node.Next
        next := newNode.Next
        node.Next = next
        if next != nil {
            newNext := next.Next
            newNode.Next = newNext
        }
    }

    return res
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值