题解 | #复杂链表的复制#

复杂链表的复制

https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba

package main

/*
type RandomListNode struct {
    Label int
    Next *RandomListNode
    Random *RandomListNode
}
*/

/**
 *
 * @param pHead RandomListNode类
 * @return RandomListNode类
*/
func Clone( head *RandomListNode ) *RandomListNode {
    //write your code here
    // 1. 克隆链表
    cloneNode(head)
    // 2. 链接 random 指针
    connectRandomLink(head)
    // 3. 拆分链表
    return ReconnectLinkList(head)
}

func cloneNode(head *RandomListNode) {
    head1 := head
    for head1 != nil {
        clone := &RandomListNode{
            Label: head1.Label,
            Next: head1.Next,
        }
        head1.Next = clone
        head1 = clone.Next
    }
}

func connectRandomLink(head *RandomListNode) {
    head1 := head

    for head1 != nil {
        clone := head1.Next
        if head1.Random != nil {
            clone.Random = head1.Random.Next
        }
        head1 = clone.Next
    }
}

func ReconnectLinkList(head *RandomListNode) *RandomListNode {
    head1 := head
    var cloneHead *RandomListNode
    // clone head
    if head1 != nil {
        cloneHead  = head1.Next
        head1.Next = cloneHead.Next
        head1 = head1.Next
    }

    cloneNode := cloneHead
    for head1 != nil {
        cloneNode.Next = head1.Next
        cloneNode = cloneNode.Next
        head1.Next = cloneNode.Next
        head1 = head1.Next
    }
    return cloneHead
}

part1 :克隆链表,为每一个节点克隆一个节点并将其插入到旧节点之后;

part2:为每一个新节点链接 random 指针;

part3:将链表拆分为新旧两个链表,返回新链表的头指针。

全部评论

相关推荐

09-17 17:09
门头沟学院 Java
雨忄:有人给出过解法,拖晚点去,然后到时候再找其他理由商量,既增加他们的筛人成本,不一定会给你收回offer ,也能占位避免工贼
秋招的嫡长offer
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务