Leetcode138.复制带随机指针的链表

138.复制带随机指针的链表(运行代码参考于力扣官网第三种答案)
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的深拷贝。
Leetcode138.复制带随机指针的链表_第1张图片
思路:
1.遍历原来的链表并拷贝每一个节点,将拷贝节点放在原来节点的旁边,创造出一个旧节点和新节点交错的链表。

如你所见,我们只是用了原来节点的值拷贝出新的节点。原节点 next 指向的都是新创造出来的节点。

2.迭代这个新旧节点交错的链表,并用旧节点的 random 指针去更新对应新节点的random 指针。比方说 B 的 random 指针指向 A ,意味着 B’ 的 random 指针指向 A’ 。

3.现在 random 指针已经被赋值给正确的节点, next 指针也需要被正确赋值,以便将新的节点正确链接同时将旧节点重新正确链接。

/*
// Definition for a Node.
class Node {
    public int val;
    public Node next;
    public Node random;

    public Node() {}

    public Node(int _val,Node _next,Node _random) {
        val = _val;
        next = _next;
        random = _random;
    }
};
*/
class Solution {
    public Node copyRandomList(Node head) {
        if(head==null){
            return null;
        }
        Node ptr=head;
        while(ptr!=null){
            Node newNode=new Node(ptr.val);
            newNode.next=ptr.next;
            ptr.next=newNode;
            ptr=newNode.next;
        }
        ptr=head;
        while(ptr!=null){
            ptr.next.random=(ptr.random!=null) ? ptr.random.next:null;
            ptr=ptr.next.next;
        }
        Node original_ptr=head;
        Node weaved_ptr=head.next;
        Node newHead=head.next;
        while(original_ptr!=null){
            original_ptr.next=original_ptr.next.next;
            weaved_ptr.next=(weaved_ptr.next!=null) ? weaved_ptr.next.next:null;
            original_ptr=original_ptr.next;
            weaved_ptr=weaved_ptr.next;
        }
        return newHead;
    }
}

你可能感兴趣的:(数据结构与算法学习)