138. Copy List with Random Pointer - Medium

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

 

M1: extra space, 用hash map

用hashmap遍历一遍list,存下每个节点,key是当前node,value存复制的node,map.put(cur, new RandomListNode(cur.label))。再遍历一遍,copy list,除了next,random指针也要复制

time: O(n), space: O(n)

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head == null) {
            return head;
        }
        HashMap<RandomListNode, RandomListNode> map = new HashMap<>();
        RandomListNode cur = head;
        while(cur != null) {
            map.put(cur, new RandomListNode(cur.label));
            cur = cur.next;
        }
        cur = head;
        while(cur != null) {
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);
            cur = cur.next;
        }
        return map.get(head);
    }
}

 

M2: 不用extra space, interweave structure

time: O(n), space: O(1)

posted @ 2018-12-26 16:23  fatttcat  阅读(122)  评论(0编辑  收藏  举报