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

题目描述:

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。

要求返回这个链表的 深拷贝。 

 

带有随机指针的链表结构

class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}

解法一:利用哈希表

K存原链表中的节点,V存原链表节点的拷贝。

 

时间复杂度:O(N)

空间复杂度:使用额外空间哈希表O(N)

class Solution {
    public Node copyRandomList(Node head) {
        HashMap<Node,Node> map = new HashMap<Node,Node>();
        Node cur = head;
        //遍历链表,把原链表和原链表的拷贝存进去
        while(cur != null){
            //构造函数中同时设置了随机节点
            map.put(cur,new Node(cur.val));
            cur = cur.next;
        }

        cur = head;
        while(cur != null){
            //cur --> 原链表节点
            //map.get(cur) --> 原链表节点的拷贝节点
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);
            cur = cur.next;
        }
        //头节点的拷贝节点,就是拷贝后链表的头节点
        return map.get(head);
    }
}

 解法二:原地空间迭代

 

时间复杂度:O(N)

空间复杂度:O(1)

public Node copyRandomList(Node head) {
        if(head == null){
            return null;
        }
        Node cur = head;
        Node nextNode = null;
        Node copyNode = null;
        //遍历生成拷贝节点,连接到原节点后面
        while(cur != null){
            nextNode =  cur.next;
            copyNode = new Node(cur.val);
            cur.next = copyNode;
            copyNode.next = nextNode;
            cur = nextNode;
        }
        cur = head;
        //设置拷贝节点的随机节点
        while(cur != null){
            nextNode = cur.next.next;
            //拷贝节点的头节点
            copyNode = cur.next;
            copyNode.random = cur.random == null ? null : cur.random.next;
            cur = nextNode;
        }

        Node res = head.next;
        //拆链表
        cur = head;
        while(cur != null){
            nextNode = cur.next.next;
            copyNode = cur.next;
            cur.next = nextNode;

            copyNode.next = nextNode == null ? null : nextNode.next;
            cur = nextNode;
        }
        return res;
    }

 

posted @ 2020-09-28 11:47  硬盘红了  阅读(102)  评论(0编辑  收藏  举报